Utility Type ReturnType

I'd like to start by saying that I am doing this series to learn and understand better Typescript, so feel free to correct me or contact me.

ReturnType<Type>

Constructs a type consisting of the return type of function Type.

Let's see some examples:

type T0 = ReturnType<() => string>; //string

type T1 = ReturnType<(s: string) => void>; // void

type T2 = ReturnType<<T>() => T>; // unknown

type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // numver[]

So what do we know so far?

Our type should:

  • Receive a function
  • Infer and return the returning type of that function if there is any

Let's see the type.

type MyReturnType<T> = T extends (...args: any) => infer R ? R : any;

Let's break it down

We accept a type T and we check that type extends a function and if it returns something T extends (...args: any) => ...

Understanding the infer keyword

The infer keyword can be used within a condition in a conditional type to put the inferred type into a variable. That inferred variable can then be used within the conditional branches.

If the function returns something then we infer its type and we return that ... => infer R ? R ... otherwise, it could be anything or nothing, so we return any ... : any

That is it, thank you!