typestar

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

  1. T extends X ? A : B chooses at the type level.
  2. infer U captures the matched inner type.
  3. never removes a case from a union.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Conditional types, step 1 of 12 in Type-level programming.

Next →