typescript · level 3 · unit 4 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is an if for types.
T extends string ? "text" : "other" reads like a question: does T fit inside string? If yes, the type after the ? is the answer. If not, the type after the : is. This is a conditional type, and the checker answers it before the code runs.
Here extends means fits inside, as it does in a constraint. Answers can hold more questions, like a chain of else if. Conditional types shine in generics, where the answer depends on what the caller passes in.
type Kind<T> = T extends string ? "text" : T extends number ? "number" : "other";
const a: Kind<string> = "text";
const b: Kind<number> = "number";
const c: Kind<boolean> = "other";
console.log(a, b, c); Read ? as “then” and : as “otherwise”.
guess first
Is it a list? What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type IsList<T> = T extends unknown[] ? "yes" : "no";
const first: IsList<string[]> = "yes";
const second: IsList<string> = "yes";
console.log(first, second);
your turn
Your turn. Teach the animals their sounds.
Fill in each sound so it matches what Sound picks for that animal.
fix it
The payloads are the wrong way round. Fix the type.
- The checker says a user payload cannot have a
name. Which answer doesPayload<"user">pick? "user"fits inside"user", so it takes the type after the?. That one has the total.- Swap the two answers on line 1, so
{ name: string }comes straight after the?.
nailed it
your types can make decisions now. :D
A extends B ? X : YpicksXwhenAfits insideB.- Chain questions in the answer, like
else if. - The checker answers conditional types before your code runs.
new words in your collection
- conditional type
This lesson isn’t saved. A free account remembers every lesson you finish.