Ask a value which member of its union it holds, like a till that looks at cash or card before it opens the drawer. Check it with typeof, with three equals signs or as its own condition, see which type TypeScript gives it inside the check and in the else, add up a week of minutes, and avoid the check that quietly loses a zero.
TypeScript
Fundamentals
Narrowing with `typeof`, equality, and truthiness. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
On Sunday evening the sheet on the fridge is full: 30 minutes of
chores on Monday, 45 on Tuesday, and sick on Wednesday. You want one
number for the week, so you put let total = 0; above the loop from
lesson 7.1 and total += entry; inside it. TypeScript refuses the
second line: Operator '+=' cannot be applied to types 'number' and 'string | number'. It is right. Wednesday holds a word, and a word
cannot be added to a number of minutes.
The till in lesson 7.1 had the same problem with cash and cards. It
looks at what the customer handed over before it opens the drawer. In
this lesson you write that check in code. By the end you can ask a
value which member of its union it holds, with typeof, with === or
with the value itself as the condition. You can say which type
TypeScript gives it on each side of the check, and the week adds up.
You also meet the one check that quietly loses a zero.
Ask a value what kind it is
typeof is an operator you write in front of a value. It gives back,
as a string, the name of the value's kind: "number", "string" and
a few more. The types you write after a colon are gone when Node runs
the program; typeof is JavaScript, so Node runs it, and it asks
about the value that is in the box at the moment the line runs. Run
it:
It prints number, string, boolean, undefined, object and
object again. The answer is always one of a few lower-case words. A
list says object, and so does every object from Module 6, so
typeof tells a string from a number, but not a list from an object.
It even says object for null, an old mistake in JavaScript that
can no longer be fixed without breaking older programs.
typeof as a check
Put typeof in an if, and TypeScript narrows the type, as it did
for !== undefined in lesson 3.5: on the lines the check protects it
uses a smaller type, and each branch knows which member it got. Press
Next branch to walk through them, or let it play:
entry:string | number
If typeof entry === "number", entry is numbertypeof entry === "number"→numbertotal += entry is allowed
Otherwise, entry is stringelse→string.toUpperCase() is allowed
One typeof check: each branch knows which member it got
All 2 branches shown.Branch 1 of 2: If typeof entry === "number", entry is numberBranch 2 of 2: Otherwise, entry is string
All 2 branches shown.
Now the sheet adds up its week. Press Run:
week.tsts
type Entry = string | number;const week: Record<string, Entry> = { Monday: 30, Tuesday: 45, Wednesday: "sick",};let total = 0;for (const [day, entry] of Object.entries(week)) { if (typeof entry === "number") { total += entry; console.log(`${day}: ${entry} min`); } else { console.log(`${day}: ${entry.toUpperCase()}`); }}console.log(`Total: ${total} min`);
It prints Monday: 30 min (min for minutes), Tuesday: 45 min,
Wednesday: SICK and Total: 75 min. Line 11 adds entry to the
total, and line 14 calls .toUpperCase() on it, and TypeScript allows
both: on line 11 the value can only be a number, on line 14 only a
string. Copy the file into VS Code (Visual Studio Code, your editor)
and hover over entry on those two lines to see number and
string.
A typeof check compares the word with ===, so the word on the
right is a plain string, and a typo in it would make a check that is
never true. TypeScript knows the eight words typeof can give and
refuses any other. Press Run: the typo stops with lesson 7.2's
TS2367 (TS for TypeScript, then the number of the message), and its
message lists all eight:
typo.tsts
function minutes(entry: string | number): void { if (typeof entry === "nubmer") { console.log(entry); }}
Two of them, bigint and symbol, name kinds of value Level 1 does
not use (Level 2 has a lesson on them), and function is what
typeof says for a function.
=== narrows to one value
typeof sorts values by their kind. === asks a sharper question: is
it this one exact value? Inside if (entry === "sick"), the box holds
exactly "sick", so TypeScript gives entry the literal type
"sick" of lesson 2.6. That is what lesson 7.2 promised about if (chore === "done"): there chore is "done". The same works on a
plain string: inside if (typed === "done"), a typed of type
string is "done", so it fits a box of Status there.
What the else gets depends on the union. In lesson 3.5, default
kept all of string, because TypeScript has no way to write "every
string except add". A union of literals is different: TypeScript can
write the words that are left. Here are both, a status of lesson
7.2's Status beside the week's entry:
status === "todo"entry === "sick"Inside
"todo"
"sick"
Else
"done"
Entry
On a union of literals the else gets the word that is left;
on an Entry it gets the whole union
So after === "sick", a chain still has to ask typeof before it
can add minutes. As lesson 3.5 showed, an else if knows what the
questions above it took away:
notes.tsts
type Entry = string | number;const thisWeek: Entry[] = [30, "sick", 45, "rest"];let sickDays = 0;let total = 0;for (const entry of thisWeek) { if (entry === "sick") { sickDays += 1; } else if (typeof entry === "number") { total += entry; } else { console.log(`Note: ${entry}`); }}console.log(`Total: ${total} min, sick days: ${sickDays}`);
It prints Note: rest, then Total: 75 min, sick days: 1. On
line 9 entry is still an Entry; the typeof question there
splits it into number on line 10 and string on line 12.
A value as its own condition
Lesson 3.5 used a box as its own condition, if (typedTask), to take
undefined away. That is called a truthiness check: the if runs
when the value is truthy, as lesson 3.2 defined it. On a union that
holds numbers or strings, it sends more than undefined to the
else, and the type TypeScript gives the else says so.
A string has one falsy value, "", and a number has two you will
meet, 0 and NaN (short for not a number), so a string or a
number can land in the else too, and TypeScript keeps string and
number in its type. On Entry | undefined, entry is an Entry
inside if (entry), but in the else it is still Entry | undefined. Here is where each value goes, beside the check that names
undefined:
entry holdsif (entry)if (entry !== undefined)45
Inside
Inside
"sick"
Inside
Inside
0
Else
Inside
""
Else
Inside
undefined
Else
Else
The check
if (entry) sends 0 and the empty string to the else;
!== undefined sends only undefined
Predict before you run
The if below has no else. Its block ends with return, which ends
the call there, as in lesson 5.1, so the function stops whenever the
check is true. Decide which type entry has on the last line of the
function.
Predict
Hover over entry on line 7. Which type does VS Code show?
Lesson 7.1 checked the sheet's Map with entry !== undefined. if (entry) is shorter and seems to mean the same, so people swap one for
the other. Lesson 3.5 showed it also turns away ""; on a number it
turns away 0, the trap that || set in lesson 3.4, and TypeScript
says nothing about it.
Common mistake
Using if (entry) where 0 is a real value
On Friday you rested on purpose, so you wrote 0. Then the program
checks each day with the shorter check:
sheet.tsts
type Entry = string | number;const sheet = new Map<string, Entry>();sheet.set("Thursday", 45);sheet.set("Friday", 0);for (const day of ["Thursday", "Friday", "Monday"]) { const entry = sheet.get(day); if (entry) { console.log(`${day}: ${entry}`); } else { console.log(`${day}: not written yet`); }}
TypeScript finds nothing wrong, and the run prints Thursday: 45,
Friday: not written yet and Monday: not written yet. Friday was
written: 0 is falsy, so it took the else with Monday, which nobody
has written yet.
Friday: not written yet
The fix
Check for the nothing you mean, undefined:
sheet.tsts
type Entry = string | number;const sheet = new Map<string, Entry>();sheet.set("Thursday", 45);sheet.set("Friday", 0);for (const day of ["Thursday", "Friday", "Monday"]) { const entry = sheet.get(day); if (entry !== undefined) { console.log(`${day}: ${entry}`); } else { console.log(`${day}: not written yet`); }}
Now it prints Friday: 0, and only Monday is not written yet. To spot
this before it happens, write entry inside the else of if (entry) for a moment and hover over it: VS Code shows Entry | undefined. If a check's else still holds number or string, a
0 or a "" can land there; if you did not mean that, check !== undefined instead.
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 check TypeScript refuses
entry is an Entry, and each {} is an empty block: only the
checks matter here. Which of these lines does TypeScript refuse?
ts
type Entry = string | number;function check(entry: Entry): void { if (typeof entry === "number") {} if (typeof entry === "String") {} if (typeof entry === "undefined") {}}
Exercise · Fix the error
Make shout work for both members
In lesson 7.1, TypeScript refused .toUpperCase() in shout,
because a number has no such method. Fix the function so the program
prints Monday: 30 MIN, then Wednesday: SICK.
Loading the editor…
Exercise · Predict the result
What a truthiness check leaves in the else
Which type does minutes have on line 5, in the else?
ts
function show(minutes: number | undefined): void { if (minutes) { console.log(`${minutes} min`); } else { console.log(minutes); }}
Exercise · Write the code
Write formatEntry
Write a function formatEntry above the console.log lines. It
takes an Entry and gives back a string:
a number of minutes, followed by min: 30 gives "30 min";
"sick" gives "ill, no chores";
any other text in capitals: "rest" gives "REST".
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does typeof entry give when entry holds 30?
Check yourself
On a box of type "todo" | "done", what is it in the else of
=== "todo"?
Check yourself
Which values does if (entry) send to the else?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Narrowing with typeof, equality, and truthiness
What things are
Word
What it means
typeof
Gives a value's kind as a string while the program runs
Truthiness check
A value used as the condition: if (entry)
Code
Write
What TypeScript knows
typeof x === "number"
Inside: number; else: the other members
x === "sick"
Inside: the literal type "sick"
status === "todo"
On "todo" | "done", the else is "done"
if (x)
Inside: no undefined; else: still the whole union
x !== undefined
Inside: every value but undefined, 0 included
Rules
Rule
What it means
The else of ===
A literal union: the words left; else the whole type
A block that returns
The lines after it get what the check did not take
0, NaN and "" are falsy
if (x) sends them to the else
A misspelled typeof word
Refused with TS2367
Lists, objects and null
typeof says "object" for all of them
Where to go next
You can now ask a value which member of its union it holds, with
typeof, with === or as its own condition, and say which type
TypeScript gives it inside the check and in the else. The week's
minutes add up, and a 0 is no longer mistaken for a day nobody
wrote.
Next is Narrowing with the in operator. typeof says
"object" for every object, so it cannot tell two shapes of object
apart; the next lesson checks which properties an object has
instead.
Before you move on, open TaskKit's index.ts in VS Code and add
these lines inside the loop of printList, under the line that
prints a task:
index.tsts
if (task.status === "todo") { console.log(" still to do"); } else { console.log(` ${task.status}`); }
Hover over task.status in the else and check that it says
"done", then run the check from lesson 7.2 with tsc (the
TypeScript compiler, which npx starts): npx tsc --noEmit--types node --allowImportingTsExtensions index.ts. It prints nothing: the
file passes. Delete the lines again once you have seen it.