Last updated: Feb 28, 2024
Reading timeยท2 min
Use the ReturnType
utility type to get the return type of a function in
TypeScript.
The ReturnType
utility type constructs a type that consists of the return
type of the provided function type.
function sum(a: number, b: number): number { return a + b; } // ๐๏ธ type SumReturnType = number type SumReturnType = ReturnType<typeof sum>; // โ From a function's type type AFunctionType = (a: number, b: string) => string; // ๐๏ธ type AFunctionReturnType = string type AFunctionReturnType = ReturnType<AFunctionType>;
We used the ReturnType utility type to get the return type of a function.
When trying to get the return type of a function from a function declaration, you have to use the typeof operator.
function sum(a: number, b: number): number { return a + b; } // ๐๏ธ type SumReturnType = number type SumReturnType = ReturnType<typeof sum>;
This is because ReturnType
takes a type and not a function.
On the other hand, if you need to get the return type from a function's type,
pass it directly to ReturnType
.
// โ From a function's type type AFunctionType = (a: number, b: string) => string; // ๐๏ธ type AFunctionReturnType = string type AFunctionReturnType = ReturnType<AFunctionType>;
Notice that we didn't use the typeof
operator because we are passing a type to
the ReturnType
utility type.
void
If the function you're working with doesn't return a value, its return type will
be void
.
function myFunction(a: number, b: number): void { console.log(a); console.log(b); } // ๐๏ธ type T = void type T = ReturnType<typeof myFunction>;
If the function might return values of multiple types, its return type will be a union type.
function myFunction(a: number, b: number): string | number { return Math.random() > 0.5 ? a + b : 'bobbyhadz.com'; } // ๐๏ธ type T = string | number type T = ReturnType<typeof myFunction>;
never
If the function throws an error,
its return type will be never
.
function myFunction(): never { throw new Error('Something went wrong'); } // ๐๏ธ type T = never type T = ReturnType<typeof myFunction>;
You can learn more about the related topics by checking out the following tutorials: