typeIsArray<T>=Textends any[]?true:false;typeTest1=IsArray<string[]>;// truetypeTest2=IsArray<number>;// false// Extracting element typestypeElementOf<T>=Textends(inferE)[]?E: never;typeStrEl=ElementOf<string[]>;// stringtypeNumEl=ElementOf<number[]>;// numbertypeNoEl=ElementOf<boolean>;// never
Output
// Conditional types act like type-level if/else
Note When a conditional type receives a union as T, it distributes - the condition is applied to each union member independently. To prevent distribution, wrap both sides in brackets: [T] extends [Condition].
// Extract the resolved type from a PromisetypeUnwrapPromise<T>=TextendsPromise<inferR>?R:T;typeA=UnwrapPromise<Promise<string>>;// stringtypeB=UnwrapPromise<number>;// number// Extract function first argumenttypeFirstArg<T>=Textends(first:inferF,...rest: any[])=> any ?F: never;typeFA=FirstArg<(name: string, age: number)=>void>;// string// Extract array element typetypeArrayItem<T>=Textendsreadonly(inferE)[]?E: never;typeItem=ArrayItem<readonly["a","b","c"]>;// "a" | "b" | "c"
Output
// infer declares a type variable that TypeScript figures out from context
Note infer can only be used inside the extends clause of a conditional type. It captures whatever type fits in that position. Multiple infer clauses in the same conditional are allowed. In union position, infer produces a union; in intersection position (like function params), it produces an intersection.
Frequently asked questions
How does TypeScript handle infer keyword?
TypeScript covers this with 2 copy-ready snippets on this page. The "Generics with Conditional Types" snippet in TypeScript uses `type Name<T> = T extends Condition ? TrueType : FalseType;`.
Which code does the TypeScript example use?
The "Generics with Conditional Types" snippet uses `type Name<T> = T extends Condition ? TrueType : FalseType;`, from the Generics section of the TypeScript cheat sheet.
What other TypeScript snippets are shown for "infer keyword"?
Besides "Generics with Conditional Types", this page also shows "infer Keyword".
Is there anything to watch out for?
Yes. For "Generics with Conditional Types": When a conditional type receives a union as T, it distributes - the condition is applied to each union member independently. To prevent distribution, wrap both sides in brackets: [T] extends [Condition].