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 : Y
  • infer R captures sub-types
  • Distributive over naked unions
  • [T] extends [U] disables distribution

More most-asked TypeScript Developer questions

← All TypeScript Developer questions