Give a value that comes in more than one kind a type of its own with |, like a fridge sheet of minutes where one day says “sick”. See why TypeScript allows a line on a union only when every member allows it, read which member an error names, and put the parentheses of (string | number)[] in the right place.
TypeScript
Fundamentals
Union types. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
The sheet on the fridge from the last lesson has a new line. On
Wednesday you were ill and did no chores at all, so next to
Wednesday you wrote a word instead of minutes: sick. The sheet
is still right. It is the type that is too strict:
Record<string, number> says every day holds a number, and
TypeScript refuses Wednesday with
Type 'string' is not assignable to type 'number'.
Think of the till in a corner shop. It takes cash or a card, and
because a customer may bring either, it only does what works for both:
it takes the amount and prints a receipt. Counting the change works
only for cash, so the till asks which one it got before it opens the
drawer. In this lesson you write types that work like that till's
rule: a value that may be one of several kinds. By the end you can
give the sheet a type that holds Wednesday, say which lines TypeScript
allows on such a value, read its refusal when it does not, and put the
parentheses of a list type in the right place.
One value, more than one kind
You have joined types with | since lesson 3.3, where string | undefined read "string or undefined", and lesson 4.6 joined two
ordinary types the same way: VS Code (Visual Studio Code, your editor)
called ["buy milk", 25] a (string | number)[]. string | number
is "a string or a number". A type joined from others with | is a
union type, or a union, and each type in it is a member.
You can join more than two the same way: string | number | boolean.
A union lets in a value of any one of its members. The value itself is
never both: 30 is a number and "sick" is a string, and a box of
string | number holds one of them at a time. In the figure, TS2322
(TS for TypeScript, then the number of the message) is lesson 2.2's
code for a value the box refuses.
The valuenumberstringstring | number30
Holdsit
TS2322
Holdsit
"sick"
TS2322
Holdsit
Holdsit
true
TS2322
TS2322
TS2322
The box's type
A union lets in a value of any of its members, and nothing else
true is neither a string nor a number, so the union refuses it
with Type 'boolean' is not assignable to type 'string | number'.
Now give the fridge sheet a union for its values, and run it:
It prints Monday: 30, Tuesday: 45 and Wednesday: sick. Copy it
into VS Code and hover over entry: its type is string | number,
the type of the sheet's values.
The order of the members does not matter. number | string is the
same type as string | number, and TypeScript's messages may list
the members in an order of their own.
Only what every member can do
On a line that uses entry, TypeScript does not know which member
it holds: the sheet decides that when the program runs. So it does
what the till does: it allows a line only if every member allows
it.
Each line below uses entry once. Switch between them, then press
Next step to follow the check, or let it play:
Your line: reachedUses entry: string | number
string: passes✓Can a string do this?
number: passes✓Can a number do this?
Node: reachedRuns the line
TypeScript asks every member; if one says no, the line is refused
All 6 steps shown.Step 1 of 6: Your lineStep 2 of 6: stringStep 3 of 6: string: passesStep 4 of 6: numberStep 5 of 6: number: passesStep 6 of 6: Node
All 6 steps shown.
Your line: reachedUses entry: string | number
string: passes✓Can a string do this?
number: stops here✕Can a number do this?
Node: never reachedRuns the line
number stops hereProperty 'toUpperCase' does not exist on type 'number'.
TypeScript asks every member; if one says no, the line is refused
All 5 steps shown.Step 1 of 5: Your lineStep 2 of 5: stringStep 3 of 5: string: passesStep 4 of 5: numberStep 5 of 5: number: stops here. Property 'toUpperCase' does not exist on type 'number'.
All 5 steps shown.
Your line: reachedUses entry: string | number
string: stops here✕Can a string do this?
number: never reachedCan a number do this?
Node: never reachedRuns the line
string stops hereProperty 'toFixed' does not exist on type 'string'.
TypeScript asks every member; if one says no, the line is refused
All 3 steps shown.Step 1 of 3: Your lineStep 2 of 3: stringStep 3 of 3: string: stops here. Property 'toFixed' does not exist on type 'string'.
All 3 steps shown.
A template string works for both members; .toUpperCase() from lesson
2.4 and .toFixed() from lesson 2.5 each works for only one of them.
Here is one of them in a function:
Press Run: TypeScript refuses line 2 with TS2339 before anything
runs. Read its message in two parts. The first line, Property 'toUpperCase' does not exist on type 'string | number'., says the
union cannot do it. The second, Property 'toUpperCase' does not exist on type 'number'., names the member that said no: here number. The
call on line 4 passes a string, but that does not help. TypeScript
checks shout for every value its parameter allows, and the next call
could pass 30. Without TypeScript, Node would print Wednesday: SICK and then, for a call with 30, stop with TypeError: entry.toUpperCase is not a function.
The same rule refuses arithmetic, as lesson 4.6's reduce found.
total += entry, with a total that holds a number, is refused
with Operator '+=' cannot be applied to types 'number' and 'string | number'. That is right:
"sick" is not a number of minutes. To add up only the days that
hold a number, a program first has to ask which member it got,
the way the till looks before it opens the drawer. That question
is lesson 7.3's typeof.
Naming a union, and unions in lists
A union you write in several places is worth a name. A type from
lesson 6.3 names any type, a union included:
entries.tsts
type Entry = string | number;function formatDay(day: string, entry: Entry): string { return `${day}: ${entry}`;}const thisWeek: Entry[] = [30, 45, "sick"];const days = ["Monday", "Tuesday", "Wednesday"];for (let i = 0; i < days.length; i++) { console.log(formatDay(days[i], thisWeek[i]));}
It prints the same three lines as week.ts. Entry[] is a list
whose every item is an Entry. Hovers and error messages now say
Entry where they said string | number; the second line of an
error still names the member that said no. Without the name, you
write that
list as (string | number)[], the type lesson 4.6 showed for
["buy milk", 25]. The common mistake below is about those
parentheses.
Unions you have already met
Lesson 3.3's refusal of .trim() on string | undefined was the
till's rule too: undefined is a member, and it has no .trim().
When the member that says no is undefined (or null), TypeScript
prints a message of its own, TS18048: 'typedTask' is possibly 'undefined'. Lesson 6.9 met a union too: for an outline written with
type, Object.entries gave the values string | number, and
.toUpperCase() on them was refused with the message this lesson
reads.
Lesson 3.5's narrowing works on any union: !== undefined takes
undefined away and leaves the other members. Keep the sheet in a
Map from lesson 6.10, with Entry for its values, so a day nobody
wrote comes back as undefined. Its get then gives Entry | undefined, which is string | number | undefined. Switch between the
two days, then press Next step, or let it play:
All 3 steps shown.Step 1 of 3: entry !== undefined is falseStep 2 of 3: The block runs: Thursday: not written yetStep 3 of 3: The next line
All 3 steps shown.
Here is the same check as code:
sheet.tsts
type Entry = string | number;const sheet = new Map<string, Entry>();sheet.set("Monday", 30);sheet.set("Wednesday", "sick");for (const day of ["Wednesday", "Thursday"]) { const entry = sheet.get(day); if (entry !== undefined) { console.log(`${day}: ${entry}`); } else { console.log(`${day}: not written yet`); }}
It prints Wednesday: sick, then Thursday: not written yet.
Inside the if, entry is an Entry again, so .toUpperCase()
is still refused: number has no such method.
Predict before you run
The function below gets "sick", a string. Decide which line
TypeScript refuses, if any.
Predict
Which line does TypeScript refuse? Type its number.
| joins whole types, and the square brackets [] after a type
belong to that type alone. As in lesson 4.6, the parentheses keep the
union together, and the square brackets after them make the list.
Common mistake
Writing string | number[] for a list of strings and numbers
You want a list that holds this week's entries, minutes and words
alike, so you write the two members and the list's brackets:
TypeScript reads the type as string | number[]: a string, or a
list of numbers. The list you wrote is neither, because of
"sick", so line 1 is refused and nothing runs.
Type '(string | number)[]' is not assignable to type 'string | number[]'.
The fix
Put the union in parentheses, so the brackets belong to all of it:
It prints [ 30, 45, 'sick' ]. The error shows the two types side by
side, and they differ only in the parentheses: the left type is the
one TypeScript works out for [30, 45, "sick"]; the right one is the
type you gave the box. When a type error names two types that look
almost the same, look first at their parentheses and square brackets.
Naming the union, as Entry[] does, avoids the question.
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.
Exercise · Read the code
Which value does not fit
The box starts with 30. Which line does TypeScript refuse?
ts
let entry: string | number = 30;entry = "sick";entry = 45;entry = undefined;entry = "20";
Exercise · Fix the error
Put the parentheses in place
TypeScript refuses line 2, under the 20, and line 4 with it:
done[i] cannot read a place in a plain number. Change the type on
line 2, and nothing else, so the program prints Thursday: 20, then
Friday: holiday.
Loading the editor…
Exercise · Predict the result
Which member said no
TypeScript refuses line 2 with an error of two lines. The first
ends on type 'string | number'. Which type does the second line
name?
ts
function round(entry: string | number): void { console.log(entry.toFixed(1));}
Exercise · Write the code
Count the sick days
Write two things above the last two lines, so the program prints
2:
a type Entry for a string or a number;
a function countSick that takes a list of Entrys and gives
back how many of them are "sick".
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What can a box of string | number hold?
Check yourself
Which lines does TypeScript allow on a union value?
Check yourself
What does the type string | number[] hold?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Union types
What things are
Word
What it means
Union type
Types joined with |: a value of any one of them
Member
One of the types in a union
Code
Write
What you get
string | number
A string or a number
type Entry = string | number;
A name for the union
(string | number)[]
A list of strings and numbers
string | number[]
A string, or a list of numbers
Rules
Rule
What it means
Any member goes in
Anything else is refused: TS2322
Only what all allow
A template string passes; .toUpperCase() does not
Second line of the error
Names the member that said no
!== undefined
Takes undefined away: Entry | undefined is Entry
Order does not matter
number | string is the same type
Where to go next
You can now write a type for a value that comes in more than one
kind, in a box, a parameter, a list or a Record, and give it a
name. You know that TypeScript allows a line on such a value only
when every member allows it, and you can read which member said no.
Next is Literal types and unions of literals. There the members
are not whole types such as string, but single values, such as
"todo" | "done", and TaskKit's tasks get a status that can only
be one of a few words.
Before you move on, copy entries.ts into VS Code. Add "Thursday"
to days and true to thisWeek, and read the error. Then give
Entry a third member, so the program runs and prints Thursday: true.