Sub topic 2
Conditional types: choosing a type with extends
This chapter assumes you know generics and union types, and that you have read the earlier chapter on mapped types.
Conditional types
A conditional type picks one of two types. It uses the form T extends U ? X : Y. If T is assignable to U, the result is X. Otherwise the result is Y.
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<number>; // falseDistribution over unions
When the checked type is a bare type parameter, TypeScript checks each member of a union separately and joins the results back into a union. This is called distribution. To turn it off, wrap both sides of extends in a tuple.
type ToArray<T> = T extends unknown ? T[] : never;
type ToArrayNonDist<T> = [T] extends [unknown] ? T[] : never;
type D = ToArray<string | number>; // string[] | number[]
type N = ToArrayNonDist<string | number>; // (string | number)[]Extracting types with infer
infer declares a type variable inside the extends clause. TypeScript fills it with whatever part of the type matches, and you can use it in the true branch.
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
type R = MyReturnType<() => Promise<string>>; // Promise<string>
type E = ElementOf<number[]>; // numberRebuilding the built-in utility types
Several built-in helpers are short conditional types. Returning never removes a member from a union, because a union with never in it simplifies away the never.
type MyExclude<T, U> = T extends U ? never : T;
type MyExtract<T, U> = T extends U ? T : never;
type MyNonNullable<T> = T extends null | undefined ? never : T;
type MyParameters<T> = T extends (...args: infer P) => any ? P : never;
type E1 = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"
type E2 = MyExtract<string | number, number>; // number
type E3 = MyNonNullable<string | null>; // string
type E4 = MyParameters<(x: number, y: string) => void>; // [x: number, y: string]| Helper | Pattern |
|---|---|
| `Exclude` | distribute, return `never` on a match |
| `Extract` | distribute, keep only matches |
| `ReturnType` | `infer` in the return position |
| `Parameters` | `infer` in the parameter list |
Exercise
Write PromiseValue<T> that gives the resolved type of a Promise, or T itself if T is not a Promise. What is PromiseValue<Promise<number> | string>?
Show answer
type PromiseValue<T> = T extends Promise<infer U> ? U : T; It distributes over the union, so the result is number | string.
Exercise
Why does MyExclude<"a" | "b", "a"> give "b" and not never?
Show answer
T is a bare type parameter, so the check runs once per member. "a" becomes never and "b" stays "b". The union never | "b" simplifies to "b".