Skip to content
loading...

re: Notes on TypeScript: ReturnType VIEW POST

FULL DISCUSSION
 

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
code of conduct - report abuse