General form
T extends U ? X : YSelects one of the 2 types: X or Y
Evaluation of the conditional type expression:
Distributivity
// Remove types from T that are assignable to U
type Diff<T, U> = T extends U ? never : T;
type TheDiffResult = Diff<"a" | "b" | "c" | "d", "a" | "c" | "f">; // "b" | "d"T extends U ? X : Y;
// When T = A | B | C it resolves to
(A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y);
Example:
Non recursive
Just like union and intersection types
type ElementType<T> = T extends any[] ? ElementType<T[number]> : T; // ErrorNot true anymore starting with TypeScript 4.1
Is not possible to use infer outside of CT
// This is not supported
type SomeType<T extends (...args: any[]) => infer R> = R;Extracting the return type of a function
type AnyFunction = (...args: any[]) => any;
type ReturnType<T extends AnyFunction>
= T extends (...args: any[]) => infer R ? R : any;TypeScript already comes with a default type
ReturnType<T>TypeScript ships with some predefined CT
Exclude<T, U> — Exclude from T those types that are assignable to U.
Extract<T, U> — Extract from T those types that are assignable to U.
NonNullable<T> — Exclude null and undefined from T.
ReturnType<T> — Obtain the return type of a function type.
InstanceType<T> — Obtain the instance type of a constructor function type.