×

typescript · level 3 · unit 4 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

captures part of a type inside a question.

Sometimes you want a piece of a type: the item type of a list, or the value inside a Promise. In the extends part of a conditional type, infer Item says: whatever type sits here, call it Item, so I can use it in the answer.

T extends (infer Item)[] ? Item : never asks: is T a list of something? If it is, the answer is that something. For string[] you get string. For a type that is not a list you get never.

type ItemOf<T> = T extends (infer Item)[] ? Item : never;
type Unwrap<T> = T extends Promise<infer Value> ? Value : T;
const names = ["Ada", "Grace"];
const one: ItemOf<typeof names> = "Alan";
const score: Unwrap<Promise<number>> = 42;
const plain: Unwrap<boolean> = true;
console.log(one, score, plain);

infer only works inside the extends part of a conditional type.