TypeScript Developer interview question · Most asked
Explain conditional types and the `infer` keyword.
Summary
Conditional types (T extends U ? X : Y) choose a type based on assignability. infer declares a type variable inside the extends clause to capture part of a type, e.g. a function's return type or a promise's resolved value.
Longer Answer
When T is a naked type parameter, conditional types distribute over unions: ToArray<string | number> becomes string[] | number[]. Wrap in brackets ([T] extends [U]) to prevent distribution. Many built-in utilities (ReturnType, Awaited, Exclude) are conditional types.
Code Example
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type ElementType<T> = T extends readonly (infer E)[] ? E : T;
type UnwrapPromise<T> = T extends Promise<infer V> ? UnwrapPromise<V> : T;
type A = MyReturnType<() => number>; // number
type B = ElementType<string[]>; // string
type C = UnwrapPromise<Promise<Promise<boolean>>>; // boolean
Key Points
T extends U ? X : Yinfer Rcaptures sub-types- Distributive over naked unions
[T] extends [U]disables distribution
More most-asked TypeScript Developer questions
- Explain `any`, `unknown` and `never`.
- What are the differences between `interface` and `type` aliases?
- What is structural typing in TypeScript?
- What is type narrowing and what techniques does TypeScript support?
- What are discriminated unions and why are they powerful?
- What are generics and how do constraints work?
- Which built-in utility types do you use most, and what do they do?
- What is TypeScript and what problems does it solve?