typescript · level 3 · unit 4 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A list, and something that is not. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type ItemOf<T> = T extends (infer Item)[] ? Item : "not a list";
const a: ItemOf<number[]> = 5;
const b: ItemOf<string> = "not a list";
console.log(a, b);
your turn
Your turn. Unwrap a promise by hand.
Capture the type inside the Promise, use it as the answer, then pick a score.
fix it
The shopping basket type will not build. Fix it.
- Read the error:
TS2304says the checker cannot find a type calledItem. Itemis not a type that exists yet. You want the checker to capture it fromT.- Write
(infer Item)[]in place ofItem[]on line 1.
nailed it
you can pull types apart with infer. :D
infer Namecaptures part of a type insideextends.T extends (infer Item)[] ? Item : nevergets a list's item type.Promise<infer Value>gets the value a promise will hold.
new words in your collection
- infer
This lesson isn’t saved. A free account remembers every lesson you finish.