TypeScript's infer keyword lets you extract a type from within a conditional type expression — one of the most powerful features in the type system.
// Extract the return type of any function:
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Extract the element type of an array:
type Unpack<T> = T extends (infer E)[] ? E : T;
// Unwrap a Promise:
type MyAwaited<T> = T extends Promise<infer V> ? V : T;Implement three runtime utilities that mirror the same logic at the value level:
| Function | Behaviour |
|---|---|
getReturnType(fn) | Calls fn() and returns its result |
unwrapArray(val) | Returns val[0] if val is an array, else val |
unwrapPromise(val) | Awaits val if it is thenable, else returns val |
The TypeScript signatures use infer-style generics to keep full type inference.
Sample tests