Give every shape of a union the same property with its own word, like a label on a parcel that says what is inside. Check that word with three equals signs or a switch, see which shape TypeScript gives the value on every branch, tell a trip from a day off, and turn TaskKit’s commands into such a union.
Fundamentals
TypeScript
Discriminated unions. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
On Friday you visit your grandmother in Lviv, and the sheet on the
fridge gets a new kind of card: a trip. Like a day off, it gives a
reason, "visit". Unlike a day off, it also says where you go. Your
week.ts now has three shapes of card, and the in check from the
last lesson fails without any error: Friday comes out as a day off.
At the post office nobody opens a parcel to find out what it is. A
label on top says "letter", "small packet" or "parcel", and that
label decides where it goes. In this lesson you give every card such
a label: a property with the same name on every shape, holding a
different word on each. By the end you can write a union like that,
check its word with === or a switch, and say which shape
TypeScript gives the value on every branch. TaskKit's commands
become such a union too.
Three shapes, and in runs out of questions
Here is the week with the trip added. The check is lesson 7.4's: it
asks about minutes, and everything else counts as a day off.
Press Run:
It prints Monday: dishes, 30 min (min for minutes), Wednesday: off, sick and Friday: off, visit, and TypeScript allows every line. As
in 7.4's exercise with a trip, in keeps every member that fits: here
the else keeps both DayOff and Trip, and both have a reason,
so line 21 is fine for both. The types are fine; the problem is the
question in asks. To tell a trip apart with in, you need a
property only a trip has:
minutesreasonplaceChore
Hasit
—
—
DayOff
—
Hasit
—
Trip
—
Hasit
Hasit
in needs a property only one card has; reason is on two
So the fix with in is one more check, "place" in entry, before the
else, because place is the one property only a trip has. It works,
but every new kind of card means hunting for a property only it has,
and checking for it in the right order. A card with no such property
cannot be told apart at all.
One property, its own word on every shape
Give every card a word that says what it is instead. Each interface
gets a property called kind, and its type is one word, a literal
type from lesson 7.2. The three interfaces are joined by a type, as
lesson 6.5's rule asks:
A union like this one is called a discriminated union: a union
of object types that all have one property with the same name, and
a different literal type in it on each member. To discriminate
means to tell things apart. The shared property is the
discriminant. kind is a common name for it, and any name works
as long as every member has it.
Every member has kind, so reading entry.kind on an Entry is
allowed, by lesson 7.1's rule. Its type is "chore" | "off" | "trip".
The word also decides what else a card must have. Put { kind: "off", day: "Wednesday", minutes: 30 } in a box typed Entry (const card: Entry = …), and TypeScript refuses it with TS2353 (TS for
TypeScript, then the number of the message): Object literal may only specify known properties, and 'minutes' does not exist in type 'DayOff'. A card that says "off" is a DayOff, and a DayOff has
no minutes.
Check the word
Lesson 7.3's === check narrowed a value to the one word it
compared with. On a discriminated union it does more: only a Chore
can hold "chore" in its kind, so inside the check TypeScript
narrows the whole entry to Chore. Press Next branch to walk
through the checks, or let it play:
entry:Chore | DayOff | Trip
If entry.kind === "chore", entry is Choreentry.kind === "chore"→Choreentry.minutes is allowed
If entry.kind === "off", entry is DayOffentry.kind === "off"→DayOffentry.reason is allowed
Otherwise, entry is Tripelse→Tripentry.place is allowed
Each check on kind leaves one shape; the else gets the last one
All 3 branches shown.Branch 1 of 3: If entry.kind === "chore", entry is ChoreBranch 2 of 3: If entry.kind === "off", entry is DayOffBranch 3 of 3: Otherwise, entry is Trip
All 3 branches shown.
Now every card carries its word, and the week prints right. Press
Run:
It prints Monday: dishes, 30 min, Wednesday: off, sick and
Friday: trip to Lviv. Line 31 reads entry.place with no check of
its own: the two checks above took the other shapes. And the order no
longer matters. Each check names the shape it means, so you can ask
about "trip" first and nothing changes.
The same check as a switch
With three or more words, a switch from lesson 3.1 often reads
better than a chain of else if. In lesson 3.5 a case "add" gave
command the type "add"; on a discriminated union each case
narrows the whole object, the same way === does:
It prints Friday: trip to Lviv. Each case ends with return, which
leaves the function, so no break is needed. There is no return
after the switch, and TypeScript does not ask for one1:
entry.kind can only be one of the three words, and each of them has
a case that returns.
friday has : Entry on its box, and that matters. Without it, as
lesson 7.2 showed, a property of an object in a box gets string, so
its kind would be plain string, and TypeScript would refuse
line(friday) with a four-line message whose last line says why:
Type 'string' is not assignable to type '"trip"'.
TaskKit: commands become a discriminated union
Now TaskKit's second step for this module. Today it reads one word,
process.argv.at(2) (argv, short for argument vector, Node's list
of the words you typed), and the add case goes back to
process.argv for the task names, from index 3. What a command is and
what it carries live in two places. Give each command a shape instead:
an add carries its titles, an unknown command carries the word that
was typed, and help, version and a missing command carry nothing.
One function reads the terminal once and gives back a Command, and
every case below reads only what its shape has.
1
Describe the commands and read them
In index.ts in ~/projects/taskkit, add these lines right above
const version = "0.1";:
A union may have a | before its first member too, so a long one can
put each member on its own line. The shapes are written out inside
Command: a union is always a type, by lesson 6.5's rule, and a
shape used only inside it needs no name of its own. In default,
word is a string, as in lesson 3.5, so it fits the unknown
shape.
2
Switch on the kind
Replace the line const command = process.argv.at(2); and the line
switch (command) { under it with these two:
Every step below is in that switch, at the bottom of the file, not
in readCommand. In its add case, the loop now walks the titles
the command carries. Replace the loop's first line,
for (let i = 3; i < process.argv.length; i++) {, and the tidyTask
line under it with these:
The titles box a few lines lower in the loop is still the list's
own titles, as before; command.titles are the ones you typed.
Under the help case, replace case undefined: with
case "missing":. Then replace the switch's default: and the two
lines under it with these three, which read the typed word from the
command:
Lesson 3.1 ended by suggesting a version command, and readCommand
now gives it a shape of its own, { kind: "version" }. If your
switch already has case "version":, keep it. If not, add the first
three lines below right above case "help":. Either way, make the
help case's line the one shown under it, which names version:
3
Check, run TaskKit, run the tests
Check the file with tsc (short for TypeScript compiler), which
npx starts, then run TaskKit and the tests:
TaskKit prints exactly what it printed before, and that is the
point: the change is in what TypeScript knows. Try it: in the
help case, change the line to
console.log(`Commands: add "task", help, version`, command.titles);
and
run the check. TypeScript stops with
Property 'titles' does not exist on type '{ kind: "help"; }'.
A shape with no name of its own is written out in full in the
message. Only an add carries titles; put the line back.
Predict before you run
Lesson 3.1 showed a case with no break running on into the
next one. Here a case has no lines at all. Decide what this
program prints.
Predict
What does this program print?
So two cases can share their lines: write the cases one under the
other, and in the lines they share, read only what both shapes have.
The common mistake: kind: string
Checking kind only works if each shape's word is written in its
type.
Lesson 7.2 showed how easily a word becomes plain string, and a
kind typed as string looks just as right.
Common mistake
A discriminant typed as string
Every card has a kind, and the check asks for "chore":
TypeScript refuses line 16 twice before anything runs: TS2339 for
chore and again for minutes, and each message has a second line
naming DayOff. With kind: string, a DayOff may hold "chore" in
its kind too, so the check proves nothing about the shape, and
entry stays an Entry.
Property 'chore' does not exist on type 'Entry'.
The fix
Write each shape's own word as the type of its kind:
Now it prints dishes: 30 min. To spot this next time: when a check
on kind leaves entry the whole union, hover over kind in
entry.kind. If VS Code (Visual Studio Code, your editor) shows
kind: string, the words are missing from the types.
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
Each exercise is checked in your browser. Press Check when you
think you have it; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What makes a union of object types a discriminated union?
Check yourself
Inside if (entry.kind === "chore"), what does TypeScript
narrow?
Check yourself
Both types have kind: string. What does a check on
entry.kind narrow?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Discriminated unions
What things are
Word
What it means
Discriminated union
Object types sharing one property, a word on each
Discriminant
That shared property, often called kind
Code
Write
What you get
kind: "chore"
A property only the word "chore" fits
entry.kind
Allowed on the union: every member has it
entry.kind === "off"
Inside: DayOff; else: the other shapes
switch (entry.kind)
In each case: the shape with that word
case "off": case "trip":
Both shapes: read what both have
return in every case
No break, no return after the switch
| { kind: "help" }
A long union, one member per line
Rules
Rule
What it means
The word picks the shape
minutes on an "off" card is TS2353
The last else
Gets the one shape no check took
Any order
Each check names the shape it means
kind: string
entry stays the union: TS2339 inside the check
Where to go next
You can now give every shape of a union a word of its own, check it
with === or a switch, and say which shape TypeScript gives the
value on every branch. The week tells a trip from a day off, and
TaskKit's commands carry what they need.
Next is Enums: reading them in other people's code, and why modern
code prefers literal unions. Older code and some libraries name a
set of words like "chore", "off" and "trip" with an enum
instead. The next lesson shows how to read one, and why the literal
words of this lesson are usually the better choice.
Before you move on, open TaskKit's index.ts in VS Code and hover
over command in case "add" and in case "unknown": in the first
it is the shape with titles, in the second the one with word. Then
hover over command in switch (command.kind): there it is the whole
Command.
Footnotes
As lesson 5.1 showed, a function whose type says
: string must give back a string on every way through it. Leave
a case out, and TypeScript stops with Function lacks ending return statement and return type does not include 'undefined'.
(TS2366). ↩
The check prints nothing. TaskKit prints:
node --test still ends with pass 7. Run node index.ts version
too: it prints the banner, then TaskKit 0.1 once more on the line
under it.
Exercise · Read the code
Which card is refused
Entry is this lesson's Chore | DayOff | Trip. Which of these cards
does TypeScript refuse as an Entry?
Exercise · Predict the result
What is left after the switch
Entry is this lesson's Chore | DayOff | Trip. Which type does
entry have on line 7?
A fourth card joins the week: a holiday. It has a day and a
reason, exactly like a day off, so no in check can tell the two
apart, and Sunday comes out as Sunday: off, Easter. Fix line so
the program prints Monday: dishes, 30 min,
Wednesday: off, sick, Friday: trip to Lviv and
Sunday: holiday, Easter.
Loading the editor…
Exercise · Write the code
Write reply for TaskKit
Here is a smaller Command with three shapes. Write a function
reply above the console.log lines. It takes a Command and gives
back a short version of TaskKit's answer:
an add command: "Adding 2 tasks", with the number of its
titles;
a help command: "Commands: add, help";
an unknown command: "Unknown command: remove", with the word
that was typed.
Loading the editor…
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkTasks added: 3 of 5, room for 2 moreList 60% fullYour list, A to Z:#3 [todo] Buy milk, due: not set#2 [todo] Call Mom, due: not set#1 [todo] Pay rent, due: not set