typescript · level 3 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Make the checker prove you handled every case.
Unions grow. Next month someone adds a gift card to Payment, and every switch that forgot it quietly does nothing. An turns that silence into an error you cannot miss.
After the last case, add a , which runs when nothing matched, and store the value in a box of type never. If every member was handled, nothing is left, so it fits. If one was missed, the checker reports TS2322 and names the member you forgot.
type Payment = { kind: "card" } | { kind: "cash" };
function fee(payment: Payment): number {
switch (payment.kind) {
case "card":
return 0.2;
case "cash":
return 0;
default:
const unreachable: never = payment;
return unreachable;
}
}
console.log(fee({ kind: "card" })); never fits in any box, so return unreachable is allowed whatever the return type.
guess first
A parrot joins the pets. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Pet = { kind: "cat" } | { kind: "dog" } | { kind: "parrot" };
function sound(pet: Pet): string {
switch (pet.kind) {
case "cat":
return "Meow";
case "dog":
return "Woof";
default:
const unreachable: never = pet;
return unreachable;
}
}
console.log(sound({ kind: "cat" }));
your turn
Your turn. Prove every coffee size is handled.
Give unreachable the type that has no values, then order one of the two sizes.
fix it
Snow arrived and the packing list broke. Fix it.
- Read the error:
TS2322names the member that reachesdefaultwithout being handled. - Snow needs wellies too. Two cases can share the same code if you stack them.
- Add
case "snow":on the line aftercase "rain":, so both share the wellies.
nailed it
the checker now spots every case you miss. :D
- In
default, store the value in aneverbox. - A forgotten member reaches
default, so the checker reportsTS2322. - Stack cases with no code between them to share one answer.
new words in your collection
- exhaustive check
- default
This lesson isn’t saved. A free account remembers every lesson you finish.