Tell the two kinds of nothing apart: undefined, which JavaScript gives to whatever was never filled, and null, which you write for empty on purpose. Write string | null and string | undefined, see why Number(null) is a quiet 0, and make TaskKit read its words with process.argv.at() so tsc catches a check in the wrong order.
Fundamentals
TypeScript
`null` and `undefined`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson's warning, "Keep the guard first", the two sides
of TaskKit's check were swapped:
typedTask.trim() !== "" && typedTask. npx tsc (tsc is short
for TypeScript compiler, the checker npx starts) found nothing
wrong. Then node index.ts add printed the banner and stopped with
TypeError: Cannot read properties of undefined (reading 'trim').
The checker you rely on let through the one line that could break,
because the type of typedTask said string, and the box held no
string at all.
Think of a form at the doctor's. One patient never gets to the
line "Allergies:" and leaves it blank. Another writes "none" on
it. Neither form lists an allergy, but they say different things:
one question was never answered, the other was answered with
nothing. JavaScript has a value for each, undefined and null.
By the end of this lesson you can tell them apart, say where each
one comes from, and write a type that lets a box hold one of them.
TaskKit's type for the task will then tell the truth, and tsc
will catch the swapped check before Node runs a line.
Two ways to say nothing
Most of the time a box holds a value: a word, a number, true.
Sometimes the honest answer is that there is nothing there, and a
program needs a way to say so, one that cannot be mistaken for a
real value. An empty string "" will not do: it is still a string,
just a short one. JavaScript has two values that mean "nothing
here", and they differ in who put the nothing there.
undefined means nothing was ever put here. JavaScript
gives it by itself: to the item of a list that does not exist,
to a box that was made but never filled.
null means empty on purpose. In the programs you write in
this course, it appears only where a person wrote it, to say
"there is no value, and that was decided".
undefined
Does: Nothing was ever put here, and JavaScript says so
A word you did not type; a box made without a value.
null
Does: Empty on purpose: a person wrote it in
A due date taken off on purpose.
undefined: nothing was put here. null: empty on purpose
Both are values of their own, not errors: you can put them in a
box, print them and compare them. Both are also on the list of
six falsy values from the last lesson, so if (!task) treats
them the same. Where they differ is what they tell the next
person who reads your code, and, as you will see, what TypeScript
lets you do with them.
A type says which nothing it allows
In Module 2 a box typed string held a string, always. That stays
true: TypeScript never lets you put null or undefined into a
string box, because every line that uses the box as a string,
.trim() included, would then have to work on nothing too.
(TaskKit's typedTask held one anyway, because TypeScript gave it
the wrong type; the TaskKit section below fixes that.)
When a box really may hold nothing, you say so in its type. You
write string | null, read "string or null": the | joins
two types, and the box may hold a value of either one. In the
same way, string | undefined is "string or undefined". Module 7
uses | to join any types you like; for now these two are all
you need.
A let can be made with a type and no =; a later line fills it.
The same box, written three times, with only its type changed:
string
Does: Holds a string
Never: Never holds undefined or null
string | undefined
Does: Holds a string, or undefined
Never: Never holds null
string | null
Does: Holds a string, or null
Never: Never holds undefined
A type lets in only the nothing it names
Why have two? A box of string | null tells the next reader that
its emptiness was decided, and TypeScript checks every line that
uses the box against that type.
Where undefined comes from
You rarely write undefined yourself: JavaScript hands it to you in
three places, and you have met two of them already.
A word that was not typed. Module 2's lesson 8 showed it:
node index.ts add has no fourth word, so process.argv[3]
(argv, short for argument vector, the list of words you typed)
asks for an item the list does not have, and gets undefined. Any
item read past the end of a list is undefined.
A box made without a value. A let made with a type and no =
holds undefined until a line fills it:
It prints undefined, then buy milk. The type has to allow it:
with plain string, TypeScript refuses the first console.log with
Variable 'pickedTask' is used before being assigned.: here the box
exists, but nothing was put in it yet, and a string box must hold
a string before anyone reads it.
An answer that holds nothing. In Module 1 you typed
console.log("TaskKit") at Node's prompt, and Node printed
TaskKit, then undefined. console.log shows its text and gives
back no value of its own, so Node printed undefined, its word for
that missing value. Module 5 explains where such answers come from,
and Module 6 adds one more place when you meet objects.
null: empty on purpose
null never turns up by accident in your code. You write it when
"no value" is the true answer and you want the program to say it was
decided: the person chose no due date, the person took the due date
off.
It prints Due: Friday, then Due: null. Why not leave the box
undefined instead? Because then a reader cannot tell "nobody
has set a due date yet" from "the due date was taken off". A
common habit, and the one this course follows: your own code uses
null for "empty on purpose", and leaves undefined to
JavaScript.
How they differ when you use them
Both mean "nothing here", but they do not behave the same once a
program uses them. Run this and compare each pair:
Used as
null
undefined
Printed
null
undefined
In a template
"null"
"undefined"
With Number()
0
NaN
As a condition
Falsy
Falsy
Compared, ===
Only to null
Only to undefined
In a template, each one becomes a word of text: Due: null, not an
empty gap. The line to remember is Number(). Number(undefined)
gives NaN (short for not a number), which Module 2's lesson 5
taught you to check for. But Number(null) gives 0, a real number
that passes every check for a number, so a missing estimate quietly
turns into zero minutes. And null === undefined is false: ===
tells the two apart, even though both are falsy.
TaskKit's type tells the truth
Now TaskKit's step for this lesson. TypeScript cannot know how many
words you will type, so for an item read by its index,
process.argv[3], it assumes the item is there and says string.
That is the type that let the swapped check through.
Lists have a second way to read an item by its index, .at().
process.argv.at(3) reads the same item as process.argv[3], and
gives back the same value, undefined included. The difference is
its type: string | undefined, because .at() is written to admit
that the item may not be there. VS Code (Visual Studio Code, your
editor) cannot show it yet: until Module 9 adds a settings file, its
hover over typedTask still says any, as lesson 2.8 warned. Your
check in the terminal is what counts, and below you will see what it
says.
Open index.ts in ~/projects/taskkit and change the two lines
that read the words:
command can be undefined too, when no word is typed at all.
In this module's first lesson that run printed Unknown command: undefined. Now
that the type names undefined, give it a case of its own, just
before default:
case undefined: is written without quotes: it matches the value
undefined, not the word. Check the file, then run TaskKit with
no command:
npx tsc printed nothing: the file passes. add "buy milk" and
add alone print what they printed before. Now repeat the
experiment this lesson started with, and swap the two sides of the
check once more, then check the file with npx tsc. Choose how the
task is read on the tabs, then press Next step to follow the
run, or let it play:
Here is what npx tsc prints for the swapped line, word for word:
TS18048 (TS for TypeScript, then the number of the error) is the
error you will meet most from now on. It says that a box whose type
allows undefined is used as if it held a value, with no check
before it. Swap the two sides back, guard first, and the error goes
away: TypeScript reads your && too, and knows that on its right
side typedTask can only be a string. Lesson 5 of this module shows
how it works that out.
Predict before you run
An estimate in minutes is read from a box that may be empty on
purpose. Decide what Number() makes of it, then what is printed.
Predict
What does this program print?
The common mistake: emptying a string box
A box made with a value gets its type from that value, as Module
2's lesson 6 showed. That is usually what you want, until the day
you try to empty it.
Common mistake
Putting null in a box TypeScript typed as string
The person takes the due date off a task, so you clear the box:
npx tsc --noEmit due.ts refuses line 2 with TS2322,
TypeScript's code for "this value does not fit this box". Line 1
gave dueDate the type string, worked out from "Friday", and
a string box never holds null.
Type 'null' is not assignable to type 'string'.
The fix
Write the type yourself, and say that the box may be emptied on
purpose:
It prints Due: null.
When TS2322 names null or undefined on one side and a type
without it on the other, the type is the thing to change, not the
value: add | null where the box may be emptied on purpose. If you
find yourself adding it to every box, stop and ask whether the
value can really be missing there.
Pass all five 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; the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
What is the difference between undefined and null?
Check yourself
A box is typed string. Which values does TypeScript let in?
Check yourself
Why does TaskKit read the task with process.argv.at(3)?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
null and undefined
What things are
Word
What it means
undefined
Nothing was put here; JavaScript gives it
null
Empty on purpose; a person writes it
| in a type
Or: the box may hold either type
string | undefined
A string, or nothing put there
string | null
A string, or empty on purpose
.at(3)
The item at index 3, typed as maybe missing
Code
Write
To
let dueDate: string | null
Make a box that may be emptied
dueDate = null;
Empty a box on purpose
process.argv.at(3)
Read a word that may not be typed
case undefined:
Match a command that was not typed
Rules
Rule
What it means
A type names its nothing
string alone holds neither
[3] trusts the list
Says string even when the item is missing
Number(null)
0, a quiet zero; Number(undefined) is NaN
Both falsy
if (!task) catches both
===
null === undefined is false
TS2322 with null
Add | null to the box's type
TS18048
Check the box before you use it
Where to go next
You can now tell the two kinds of nothing apart: undefined, which
JavaScript gives to whatever was never filled, and null, which a
person writes to mean "none, on purpose". You can write a type
that allows one of them with |, and TaskKit reads its words with
.at(), so tsc refuses any line that uses the task before
checking that it is there.
Next is Optional chaining ?. and nullish coalescing ??.
Checking a box before every use works, but it adds lines. There
you meet two operators made for boxes that may hold nothing: one
uses a value only if it is there, and one fills in a default that
keeps a real 0, which the last lesson's || could not.
Before you move on, change case undefined: to case "undefined":,
check the file and run node index.ts, and predict which line
prints before you press Enter (return on a
Mac). Then put it back.
Yourcode
TypeScript
Node
Screen
Your code: index.tsindex.tsindex.ts
TypeScript: checked ✓checked✓checked✓
Node: runs .trim()runs.trim()runs.trim()
Screen: TypeErrorTypeErrorTypeError
Time
The two sides swapped: .trim() comes first. You check with
npx tsc before you run node index.ts add, with no task.
The type says string, so .trim() looks safe. TypeScript
finds nothing wrong.
There is no item 3, so typedTask holds undefined, and
Node calls .trim() on it.
TypeError: Cannot read properties of undefined (reading 'trim'), after the banner has already printed.
With .at(3) the type says undefined too, and tsc stops the swap
All 4 steps shown.Step 1 of 4: Your code: index.tsStep 2 of 4: TypeScript: checked ✓Step 3 of 4: Node: runs .trim()Step 4 of 4: Screen: TypeError
All 4 steps shown.
Yourcode
TypeScript
Node
Screen
Your code: index.tsindex.tsindex.ts
TypeScript: 'typedTask' is possibly 'undefined'.'typedTask'ispossibly'undefined'.'typedTask'ispossibly'undefined'.
Node: not run yetnotrunyetnotrunyet
Screen: tsc's errortsc'serrortsc'serror
Time
The two sides swapped: .trim() comes first. You check with
npx tsc before you run node index.ts add, with no task.
The type says string | undefined, and .trim() runs before
any check. TypeScript stops here and names the line.
You fix the line before running it, so not one line of TaskKit
runs.
Only the check's message: the mistake was caught before any
run.
With .at(3) the type says undefined too, and tsc stops the swap
All 4 steps shown.Step 1 of 4: Your code: index.tsStep 2 of 4: TypeScript: 'typedTask' is possibly 'undefined'.Step 3 of 4: Node: not run yetStep 4 of 4: Screen: tsc's error
All 4 steps shown.
Exercise · Read the code
Which nothing was decided
A person tells TaskKit that a task has no due date. Which value
should the task's dueDate box hold?
Exercise · Predict the result
Predict an empty box in a template
What does this program print?
ts
let pickedTask: string | undefined;console.log(`Picked: ${pickedTask}`);
Exercise · Read the code
Which type lets undefined in
A box will hold the word typed after add, or undefined when
none was typed. Which type lets TypeScript accept both?
form
Name: AnaAllergies:
Left blank
form
Name: AnaAllergies: none
Written: none
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Which command? Try: node index.ts helpTasks added: 0 of 5, room for 5 moreList 0% full
Outputtext
index.ts:15:9 - error TS18048: 'typedTask' is possibly 'undefined'.15 if (typedTask.trim() !== "" && typedTask) { ~~~~~~~~~Found 1 error in index.ts:15
due.ts
let dueDate: string;dueDate = "Friday";
due.ts
let dueDate: string | undefined;dueDate = undefined;
due.ts
let dueDate: string | null;dueDate = null;
picked.tsts
let pickedTask: string | undefined;console.log(pickedTask);pickedTask = "buy milk";console.log(pickedTask);
let dueDate = "Friday";dueDate = null;console.log(`Due: ${dueDate}`);
due.tsts
let dueDate: string | null = "Friday";dueDate = null;console.log(`Due: ${dueDate}`);
Exercise · Fix the error
Let the estimate be cleared
TypeScript refuses this program. Change the type of estimate, and
nothing else, so it prints Estimate: null.
Loading the editor…
Exercise · Write the code
A due date that starts empty on purpose
Under the first line, make a box dueDate that holds a string or
null, start it at null, and print it. Then put "Friday" in
it and print it again. The program prints three lines: the
heading, null, then Friday.