TypeScript 7 reference · Type Operators and Keywords
TypeScript infer Keyword
Inside a conditional type, infer captures part of a type into a new type variable, e.g. the element type of an array.
TypeScript 7 Since 2.8
Syntax
T extends Something<infer U> ? U : Fallback
Examples
type FirstArg<F> = F extends (first: infer A, ...rest: any[]) => any ? A : never;
function greet(name: string, times: number) {
return name.repeat(times);
}
const arg: FirstArg<typeof greet> = "Ana";
console.log(greet(arg, 2));
Output
AnaAna
type Unpromise<T> = T extends Promise<infer V> ? V : T;
const v: Unpromise<Promise<number>> = 7;
console.log(v);
Output
7
Version history
| Version | Change |
|---|---|
| TypeScript 2.8 | Added |
Related
conditional types (T extends U ? X : Y)· Choose between two types based on a condition, like a ternary for types. The basis of many utility types.Awaited<Type>· Unwrap the value type of a Promise (recursively), like what await gives you. Awaited<Promise<number>> is number.- TypeScript keyof, typeof and Indexed Access · tutorial