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 the case with the same value; break or return ends it, and without them, the program falls through to the next case. default catches the rest. Every case narrows the type.
  • The exhaustiveness check in default, const unhandled: never = item; return unhandled;, makes TypeScript report every switch that has no case for some kind, and it names the kind. never is the type with no values.
  • Record<Rarity, number> is an object with exactly the keys of Rarity, and a number for each of them. A missing key is an error, and prices[item.rarity] reads a value.
  • const classes = ["warrior", "mage"] as const; is a read-only list of exact values, and type 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 a reward.
  • Instead of a boolean with optional properties, write a union, so that impossible combinations can't be written. A boolean can 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: 35

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

8/8