Literal types and unions of literals ("todo" | "done")
Give a value a type made of a few exact words, like a spreadsheet column with a drop-down of todo and done. See TypeScript refuse a misspelled word before anything runs, read its guess when only a capital letter is wrong, learn why a let box gets string instead, and give every TaskKit task a status.
TypeScript
Fundamentals
Literal types and unions of literals (`"todo" | "done"`). Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
You and two roommates keep the chores in a shared spreadsheet. Its
last column says whether a chore is finished, and everyone fills it in
their own way: done, Done, finished, and once, in a hurry,
dnoe. On Sunday you ask the sheet how many chores are finished. It
counts the cells that say exactly done and answers one, but four
chores were finished. The sheet took every word, because its column
allows any text.
A spreadsheet fixes this with a drop-down list: you give the column
two choices, todo and done, and from then on a cell holds one
of them and nothing else. In this lesson you give TypeScript the
same list. By the end you can write a type that allows only a few
exact words, read TypeScript's refusal when a word is not one of
them, and give every TaskKit task a status that can only be
"todo" or "done".
A type made of a few exact words
Lesson 2.6 showed a literal type, a type that allows exactly one
value: a const box filled with "0.1" has the type "0.1". You can
also write one yourself after a colon, like any other type. On its own
it is not much use: a box of type "done" can only ever hold
"done".
Joined with the | of lesson 7.1, literal types become the
drop-down list. "todo" | "done" is a union whose members are
single values rather than whole types such as string: a union
of literals. Give it a name with type, as lesson 7.1 named
Entry:
ts
type Status = "todo" | "done";
Here is what a box of this union lets in, beside a box of string. A
refused value shows its error code: TS for TypeScript, then the number
of the message:
string"todo" | "done""todo"
Holdsit
Holdsit
"done"
Holdsit
Holdsit
"Done"
Holdsit
TS2820
"dnoe"
Holdsit
TS2322
string lets in any text; the union lets in its two words
and nothing else
A value must match a member exactly, capital letters included:
"Done" is a different string from "done", so the union refuses it.
Its error has a code of its own, TS2820, because it adds the guess
you met in lesson 1.5: Type '"Done"' is not assignable to type 'Status'. Did you mean '"done"'? TypeScript guesses when your word is
very close to a member, as "Done" is. "dnoe", with two letters
swapped, is too far from both, so it makes no guess and gives the
plain TS2322.
Now the sheet's column becomes a list of Status, and the
program counts the finished chores:
ts
type Status = "todo" | "done";const chores: Status[] = ["done", "done", "todo"];let finished = 0;for (const chore of chores) { if (chore === "done") { finished += 1; }}console.log(`Done: ${finished} of ${chores.length}`);
It prints Done: 2 of 3. Node runs it exactly as it would run a list
of string: like every type, Status is checked by TypeScript and is
gone by the time the program runs.
The members of a union can be numbers too:
type Stars = 1 | 2 | 3 | 4 | 5; is a rating of one to five stars,
and TypeScript refuses 6 in a Stars box with TS2322.
A wrong word stops before anything runs
Now the hurried cell from the sheet: the second chore misspelled as
"dnoe". What happens to it depends on the type of the list. Switch
between the two types, then press Next step to follow it, or let
it play:
Yourcode
TypeScript
Node
Screen
Your code: done.tsdone.tsdone.ts
TypeScript: checked ✓checked✓checked✓
Node: counts donecountsdonecountsdone
Screen: Done: 1 of 3Done:1of3Done:1of3
Time
Three statuses: "done", "dnoe" and "todo". The second one
was meant to be "done".
Every item is text, and string allows any text, so TypeScript
finds nothing wrong.
Node runs the loop and counts the items that are exactly
"done": one.
One, where you finished two. The typo reached the screen as a
wrong number, and nothing said why.
With string the typo reaches the screen; with Status it
stops first
All 4 steps shown.Step 1 of 4: Your code: done.tsStep 2 of 4: TypeScript: checked ✓Step 3 of 4: Node: counts doneStep 4 of 4: Screen: Done: 1 of 3
Three statuses: "done", "dnoe" and "todo". The second one
was meant to be "done".
"dnoe" is not one of the two words, so TypeScript stops with
Type '"dnoe"' is not assignable to type 'Status'.
Node never starts, so not one line of the program runs.
Nothing reaches the screen, and the error says which word to
fix.
With string the typo reaches the screen; with Status it
stops first
All 4 steps shown.Step 1 of 4: Your code: done.tsStep 2 of 4: TypeScript: "dnoe" refusedStep 3 of 4: Node: never startsStep 4 of 4: Screen: nothing printed
All 4 steps shown.
Here is the list as a Status[], typo and all. Press Run:
done.tsts
type Status = "todo" | "done";const chores: Status[] = ["done", "dnoe", "todo"];let finished = 0;for (const chore of chores) { if (chore === "done") { finished += 1; }}console.log(`Done: ${finished} of ${chores.length}`);
Then press Edit, change Status[] to string[], and run it
again: that is the figure's other scenario.
TypeScript checks a switch from lesson 3.1 the same way. In a
switch on a Status, a case with any other word can never match, so
TypeScript refuses it:
ts
type Status = "todo" | "done";function printMark(status: Status): void { switch (status) { case "dnoe": console.log("finished"); break; }}
case "dnoe": is refused with
Type '"dnoe"' is not comparable to type 'Status'. (TS2678).
TaskKit: every task gets a status
Now TaskKit's step for this lesson: every task gets a status, and
it can only be one of the two words. A task you add is not done
yet, so it starts as "todo".
1
Name the statuses and give Task one
In index.ts in ~/projects/taskkit, put the union above interface Task, and add a status property to the interface, under the id
(short for identifier, the number that names a task), title and
due it already has:
index.tsts
type Status = "todo" | "done";interface Task { readonly id: number; title: string; due?: string; status: Status;}
2
Start every new task as todo
status has no ?, so every task must have one, and TypeScript now
refuses the push in the add case, because the new task has no
status yet, with Property 'status' is missing in type '{ id: number; title: string; }' but required in type 'Task'. Replace that line with
this one:
In printList, replace the whole for loop with this one. It
prints the status in brackets, and the due date gets a box of its
own so the line stays short enough to read:
index.tsts
for (const task of byName) { const due = task.due ?? "not set"; console.log(`#${task.id} [${task.status}] ${task.title}, due: ${due}`); }
If you rewrote the loop with { id, title, due } after lesson 6.8,
this one replaces that version too.
4
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 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
node --test still counts pass 7.
Every task now says [todo], and no line of TaskKit can give a task a
status other than "todo" or "done". Try it: change "todo" in the
push line to "Todo" and run the check again. TypeScript stops with
the TS2820 from above, Did you mean '"todo"'?, at that line. Put
the lower-case word back. Status keeps "done" all the same: a type
lists every value a box may hold, not only the ones today's code
writes.
Predict before you run
In lesson 7.1, === compared a string | number with "sick", a
value one of its members can hold. Read this function with the union
in mind, and decide whether TypeScript lets every line through.
Predict
Which line does TypeScript refuse? Type its number.
ts
type Status = "todo" | "done";function isFinished(status: Status): boolean { return status === "finished";}const rent: Status = "done";console.log(isFinished(rent));
The common mistake: a let box with no type
A union of literals asks for one of its words, and "todo" is one.
So it surprises people when a "todo" from a box of their own is
refused.
Common mistake
Passing a let box with no type where a Status is needed
You keep the rent's status in a box, because it will change once
you pay, and pass it to a function that prints a task:
ts
type Status = "todo" | "done";function printTask(title: string, status: Status): void { console.log(`[${status}] ${title}`);}let rentStatus = "todo";printTask("Pay rent", rentStatus);
TypeScript refuses line 8. As lesson 2.6 showed, a let box gets
the whole kind of its first value, string, so that it can be
refilled. A string box may hold any text later, so it is not a
Status.
Argument of type 'string' is not assignable to parameter of type 'Status'.
The fix
Write the type on the box. The box then takes only the two words,
and it fits the parameter:
ts
type Status = "todo" | "done";function printTask(title: string, status: Status): void { console.log(`[${status}] ${title}`);}let rentStatus: Status = "todo";printTask("Pay rent", rentStatus);
It prints [todo] Pay rent. A const box would have fitted with
no type written, because it keeps the literal type "todo", as in
lesson 2.6. The rent's status will change, though, so its box is a
let, and a let box needs the type written.
A const object made without a type has the same trouble: as lesson
6.2 showed, its properties can still be refilled, so a text property
gets string. const rent = { id: 1, title: "Pay rent", status: "todo" }; gives rent the type { id: number; title: string; status: string; }, and passing it where a Task is needed is refused; the
error's last line says Type 'string' is not assignable to type 'Status'. Whenever an error says that string is not assignable to
your union, find the box the value came from and write the type on it:
let rentStatus: Status, or const rent: Task for an object.
TypeScript refuses one line of this switch. Fix it so the program
prints [x] Pay rent, then [ ] Buy milk.
Loading the editor…
Exercise · Fix the error
Give the object its type
TypeScript refuses the last line, because dishes was made without
a type. Change one line, but not the values in it, so the program
prints
[done] Wash the dishes.
Loading the editor…
Exercise · Write the code
Flip the checkbox
Write a function nextStatus above the last two lines. It takes a
Status and gives back the other one: "done" for "todo", and
"todo" for "done", like a checkbox you click.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What can a box of type "todo" | "done" hold?
Check yourself
When does TypeScript catch a Status misspelled as dnoe?
Check yourself
Why is the box from let next = "todo"; refused where a
Status is needed?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Literal types and unions of literals
What things are
Word
What it means
Union of literals
Literal types joined with |: a few exact values
Code
Write
What you get
let mark: "done" = "done";
A box that holds only "done"
type Status = "todo" | "done";
A name for the two words
let mine: Status = "todo";
A box that takes only a status
const rent: Task = { … };
An object whose status stays a Status
1 | 2 | 3 | 4 | 5
Numbers work the same way
Rules
Rule
What it means
Exact match
"Done" is not "done": TS2820 suggests the member
Any other value
Refused before anything runs: TS2322
A check it never passes
status === "finished" is TS2367
A case it never matches
case "dnoe": is TS2678
let box or property
Gets string unless you write the type
const box
Keeps the literal type: "todo"
Where to go next
You can now write a type that allows only a few exact values, name
it with type, and read TypeScript's refusal of any other value,
in a box, a list, a comparison or a case. You also know why a
let box gets string instead of the literal type, and what to
write so it takes a Status. TaskKit's tasks carry a status that
can only be "todo" or "done".
Next is Narrowing with typeof, equality, and truthiness. Inside
if (chore === "done"), TypeScript knows more about chore than the
type you wrote, and the next lesson shows what it knows on each side
of a check, and how typeof tells the minutes on lesson 7.1's fridge
sheet from its words.
Before you move on, see that VS Code (Visual Studio Code, your editor)
knows the union too. Open index.ts, delete "todo" from the push
line, and type the opening quote again: the editor offers "todo" and
"done" to pick from, like the drop-down in the spreadsheet. Pick
"todo", then run the check.