DEV Community

Notes on TypeScript: ReturnType

A. Sharif on January 27, 2019

Introduction These notes should help in better understanding TypeScript and might be helpful when needing to lookup up how leverage Type...
Collapse
 
rmrfetc profile image
Rob • Edited

Apparently we can't infer the return type of a generic function based on a generic input. One of the guys in the gitter TypeScript channel gave me this example explanation.

function identity<T>(a: T) : T {
  return a;
}
interface Callable<ReturnType> {
  (...args: any[]): ReturnType;
}
type GenericReturnType<ReturnType, F> = F extends Callable<ReturnType>
  ? ReturnType
  : never;

type IdentityType = GenericReturnType<string, typeof identity>; // => string

^ example however does not actually work how it's explained...

function identity<T>(a: T) : Promise<T> {
  return Promise.resolve(a);
}
interface Callable<ReturnType> {
  (...args: any[]): ReturnType;
}
type GenericReturnType<ReturnType, F> = F extends Callable<ReturnType>
  ? ReturnType
  : never;

type IdentityType = GenericReturnType<string, typeof identity>; // never