The infer
keyword in Typescript makes it possible to extract types. This can be used to extract function parameters, generics and more.
// Given the following types ...
export interface Stream<T> { next: (value: T) => void }
export type SpecificStream = Stream<string[]>;
// ... you can extract T into a type
export type ValueOfStream<S> = S extends Stream<infer T> ? T : never;
// ... and use like this
function emitValue(
stream: SpecificStream,
value: ValueOfStream<SpecificStream> // Extract T from Stream
) {}
TypeScript provides some built-in types like Parameters
and ReturnType
.
// Given this type ...
export type SomeFn = (first: string, second: boolean) => string[];
// ... you can extract parameters
export type SecondParam = Parameters<SomeFn>[1];
// ... and the return type
export type ReturnTypeOfSomeFn = ReturnType<SomeFn>;