Conditional types and infer in TypeScript
Types that branch, and extract inner types.
type Unwrap<T> = T extends Promise<infer U> ? U : T;
type ElementOf<T> = T extends (infer U)[] ? U : never;
type NonNull<T> = T extends null | undefined ? never : T;
type A = Unwrap<Promise<string>>;
type B = ElementOf<number[]>;
type C = NonNull<string | null>;
function unwrap<T>(value: T | Promise<T>): Promise<T> {
return Promise.resolve(value);
}
How it works
T extends X ? A : Bchooses at the type level.infer Ucaptures the matched inner type.neverremoves a case from a union.
Keywords and builtins used here
PromiseTextendsfunctionnevernumberreturnstringtype
The run, in numbers
- Lines
- 11
- Characters to type
- 353
- Tokens
- 113
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 65 seconds.
Step 1 of 3 in Conditional types, step 1 of 12 in Type-level programming.