Summary
In this lesson, you learned that:
- A discriminated union is a union of object types that share a tag property, such as
kind, with a different literal type in each:type Item = { kind: "potion"; heal: number } | { kind: "weapon"; damage: number };. Checking the tag,if (item.kind === "potion"), narrows the type. TypeScript checks the properties of each kind and catches misspelled kinds. switch (item.kind)jumps to thecasewith the same value;breakorreturnends it, and without them, the program falls through to the next case.defaultcatches the rest. Everycasenarrows the type.- The exhaustiveness check in
default,const unhandled: never = item; return unhandled;, makes TypeScript report everyswitchthat has no case for some kind, and it names the kind.neveris the type with no values. Record<Rarity, number>is an object with exactly the keys ofRarity, and a number for each of them. A missing key is an error, andprices[item.rarity]reads a value.const classes = ["warrior", "mage"] as const;is a read-only list of exact values, andtype HeroClass = (typeof classes)[number];turns it into a union, so the list and the type always match.- A discriminated union can describe the states of one thing too, each with its own data: only a quest with
status: "done"has areward. - Instead of a
booleanwith optional properties, write a union, so that impossible combinations can't be written. Abooleancan be the tag too:{ isLocked: false } | { isLocked: true; keyName: string }.
In the next lesson, Generics, you'll learn to write functions and types that work with any type, while TypeScript still keeps track of which type it is: a function that returns the first element of any array, or a chest that can hold any loot. And you'll see how types with angle brackets, such as Record, work.
Now practice. Kira's journey in the editor is a list of encounters: fights, treasures, and rests.
Instructions
Run the program: the exhaustiveness check reports a kind without a case. Add the case: for a rest, describeEncounter returns Kira rests by the fire. The program then prints:
Kira fights a wolf (+20 XP)
Kira finds 35 gold
Kira rests by the fire
Kira fights a goblin (+15 XP)Below the loop, create const counts: Record<"fight" | "treasure" | "rest", number> with every count at 0, and count the encounters of each kind in it.
Also add up the XP from the fights and the gold from the treasures. At the end, print the counts and the totals:
Kira fights a wolf (+20 XP)
Kira finds 35 gold
Kira rests by the fire
Kira fights a goblin (+15 XP)
Fights: 2, treasures: 1, rests: 1
XP: 35, gold: 35Start programming for free
8/8