Get the return Type of a Function in TypeScript

avatar

Borislav Hadzhiev

Last updated: Mar 12, 2022

banner

Photo from Unsplash

Get the return Type of a Function in TypeScript #

Use the ReturnType utility type to get the return type of a function in TypeScript, e.g. type T = ReturnType<typeof myFunction>. The ReturnType utility type constructs a type that consists of the return type of the provided function type.

index.ts
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.

Note that when trying to get the return type of a function from a function declaration, you have to use the typeof operator.

index.ts
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.

index.ts
// ✅ 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.

If the function you're working with does not return a value, its return type will be void.

index.ts
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.

index.ts
function myFunction(a: number, b: number): string | number { return Math.random() > 0.5 ? a + b : 'hello world'; } // 👇️ type T = string | number type T = ReturnType<typeof myFunction>;

If the function throws an error, its return type will be never.

index.ts
function myFunction(): never { throw new Error('Something went wrong'); } // 👇️ type T = never type T = ReturnType<typeof myFunction>;
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.