Check a box for null or undefined with if, and read the type TypeScript gives it inside the check, in the else and after the block. See why a check takes away only the nothing it names, and make TaskKit tell a person who typed ADD that commands are lower case.
TypeScript
Fundamentals
Checking for `null`: a first look at narrowing. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Two lessons ago tsc (short for TypeScript compiler, the checker
npx starts) refused one line of TaskKit. The box typedTask had
the type string | undefined, and typedTask.trim() stopped the
check with TS18048 (TS for TypeScript, then the number of the
error): 'typedTask' is possibly 'undefined'. Then you put
typedTask && in front of the same call, and tsc accepted it.
Nothing about the box had changed: the same name, the same type on
the line that made it, the same .trim(). Something in between told
TypeScript that the call was now safe.
Think of an airport. Anyone can walk into the hall, with a ticket or
without one. Past the security gate is the lounge, and everyone in
it has shown a boarding pass, so nobody in the lounge asks for it
again. Walk back out, and you are in the hall, where anyone may be
standing. TypeScript treats your checks like that gate. By the end
of this lesson you can say which type a box has on any line, write a
check TypeScript understands, and make TaskKit give a hint when a
command is typed in capitals.
TypeScript reads your checks
In this module's first lesson you put the narrow question first:
added === limit lets fewer values through than added > 0. A
type can be narrow too. string | undefined allows every string
and undefined; string allows only the strings. It is the
narrower of the two.
TypeScript reads your code before Node runs it, and it reads the
conditions too. When an if asks typedTask !== undefined,
TypeScript knows that every line inside the block runs only for a
string, so there it gives typedTask the type string. That is
called narrowing: on the lines a check protects, TypeScript
uses a smaller type, one with fewer possible values. Nothing
happens to the value in the box. What changes is what TypeScript
knows about it.
Here is such a check drawn as the branch diagram from this module's
first lesson, with the type written in each block. The line after it
counts the tasks, as TaskKit's last lines do. Choose what was typed
after add on the tabs, then press Next step to follow the
check, or let it play:
After the check, each road knows more about typedTask
All 3 steps shown.Step 1 of 3: typedTask !== undefined is trueStep 2 of 3: The block runs: Added: buy milkStep 3 of 3: The next line: Tasks added: 1 of 5
After the check, each road knows more about typedTask
All 3 steps shown.Step 1 of 3: typedTask !== undefined is falseStep 2 of 3: The block runs: Add what?Step 3 of 3: The next line: Tasks added: 0 of 5
All 3 steps shown.
Whichever road a run takes, TypeScript has already worked out the
type on both of them, before anything runs. It does not know which
road a run will take. It knows that on one road the box holds a
string, and on the other it holds nothing.
This page has no terminal, so there is no word after add to read.
The box below stands in for it, made the way the last lesson made
one: a let with a type and no =. It holds undefined, as
process.argv.at(3) does after node index.ts add (argv, short
for argument vector, the list of words typed). Run the check from
the figure:
It prints Add what?, and tsc accepts .trim() on line 4. Copy
it into a new file in VS Code (Visual Studio Code, your editor) and
hover over typedTask on each line that names it: on line 2 the
type is string | undefined, on line 4 it is string. In the
else block it would be undefined, the only value left once the
strings have gone the other way.
Checks TypeScript understands
!== undefined is not the only check TypeScript reads. Every
check you have written in this module narrows the same way:
You write
Where
typedTask is
if (typedTask !== undefined)
Inside the block
string
if (typedTask === undefined)
Inside the else
string
if (typedTask)
Inside the block
string
typedTask && typedTask.trim()
Right of &&
string
The last row is the puzzle this lesson opened with. The right side
of && runs only when the left side is truthy, as lesson 2 of this
module showed, so TypeScript treats it like the inside of an if:
there, typedTask is a string, and .trim() is allowed.
if (typedTask) is the check from lesson 2 too: it also turns away
"". That is right when an empty task means nothing was typed, and
wrong when "" is a real answer.
An if / else if chain carries what it learned down to the next
question. Once the first question has taken undefined away, the
else if below it may call .trim():
It prints Add what?. The second question is asked only when the
first was false, so on line 5 typedTask is a string. Swap the
two questions and tsc refuses .trim() with TS18048, because
the first question would then run before anything was checked.
A check lasts until its block ends
The lounge has walls. A check narrows the type on the lines inside
its block. After the block, TypeScript joins what each road knows:
here one road has a string and the other undefined, so the box is
string | undefined again.
Bad — the check asks the right
question, but .trim() is called after its block has ended.
The first is refused with TS18048 on line 6. Run with Node without
checking first, it prints Add what? and then stops with a
TypeError. A program that warns about a missing task and then uses
it anyway is the kind of bug the type was written to catch.
Checking for null
Programmers say "check for null" about any check for a missing
value, and the title of this lesson does too. In code, the two
kinds of nothing are checked separately: !== undefined takes
away undefined, and !== null takes away null.
TaskKit has no null yet, so here is one on purpose. Say a person
may type a due date after the task. When they type none, the box
gets null: no due date, on purpose, the way lesson 3 used null.
?? from the last lesson does that in one line:
due.tsts
// What process.argv.at(4) holds after: node index.ts add "buy milk"let typedDate: string | undefined;// No date typed: no due date, on purposeconst dueDate = typedDate ?? null;if (dueDate !== null) { console.log(`Due: ${dueDate.toUpperCase()}`);} else { console.log("No due date");}
It prints No due date. The type of dueDate on line 4 is
string | null; inside the if it is string. Take the if away
and tsc refuses dueDate.toUpperCase() with TS18047:
'dueDate' is possibly 'null'., the twin of TS18048. The last
word of the error names the nothing that is still in the type.
A check takes away only the nothing it names. On a
string | undefined box like typedTask, three checks give three
answers:
if (typedTask !== null) {typedTask.trim();}
'typedTask' is possibly 'undefined'.
!== null
Does: Takes away null, which this box never holds
Never: Never takes away undefined: .trim() is refused
if (typedTask !== undefined) {typedTask.trim();}
typedTask: string
!== undefined
Does: Takes away undefined: inside, a string
Never: Never turns away "": it is a string too
if (typedTask) {typedTask.trim();}
typedTask: string
if (typedTask)
Does: Takes away every falsy value, null and "" too
Never: Never lets an empty string in
On string | undefined, a check removes only the nothing it names
TaskKit gives a hint for capitals
Now TaskKit's step for this lesson. Type node index.ts ADD "buy milk", and TaskKit answers Unknown command: ADD. It is right:
switch compares with ===, and capitals count. It could be more
helpful and say what went wrong.
VS Code cannot show these types in index.ts yet (until Module 9
its hover says any), but tsc works them out like this. A case
is a check too: in case "add": the type is "add", in
case undefined: it is undefined, and in default it is
string, whatever is left once the cases above have taken their
values:
command:string | undefined
If case "add", command is "add"case "add"→"add"
If case "help", command is "help"case "help"→"help"
If case undefined, command is undefinedcase undefined→undefined
If default, command is stringdefault→string.toLowerCase() is safe here
Every case is a check: default gets only what is left
So in default, command is a string, and string methods are
safe on it. .toLowerCase() from Module 2 turns ADD into add;
when that changes the word, the command was typed with capitals.
Add three lines to default:
index.tsts
default: console.log(`Unknown command: ${command}`); if (command !== command.toLowerCase()) { console.log("Commands are written in lower case"); } console.log("Run node index.ts help to see the commands");}
Check the file, then run TaskKit with a command in capitals and
with one it does not know:
npx tsc prints nothing: the file passes. The first run prints:
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Unknown command: ADDCommands are written in lower caseRun node index.ts help to see the commandsTasks added: 0 of 5, room for 5 moreList 0% full
remove has no capitals, so its run prints the same banner, then
Unknown command: remove, the line about help and the two count
lines, without the line about lower case.
Now see what case undefined was doing for you. Delete its three
lines and check the file again:
Outputtext
index.ts:31:21 - error TS18048: 'command' is possibly 'undefined'.31 if (command !== command.toLowerCase()) { ~~~~~~~Found 1 error in index.ts:31
Without that case, undefined is left for default, and
.toLowerCase() might be called on nothing. Put the three lines
back, and tsc passes again.
Predict before you run
The check below covers its block. Decide which type typedTask
has on the last line, after the block has ended.
Predict
Hover over typedTask on line 5. Which type does VS Code show?
The lesson is called "Checking for null", and !== null is the
check people write first. On a box that may hold undefined, it
checks for the wrong thing.
Common mistake
Checking for null when the box may hold undefined
You want to be sure a task was typed before you trim it, so you
check for null:
trim.tsts
let typedTask: string | undefined;if (typedTask !== null) { console.log(typedTask.trim());}
npx tsc --noEmit trim.ts refuses line 3 with TS18048. The box
can never hold null, so the check takes nothing away: inside the
block the type is still string | undefined. Run with Node alone,
the check is true for undefined, and line 3 stops with
TypeError: Cannot read properties of undefined (reading 'trim').
'typedTask' is possibly 'undefined'.
The fix
Check for the nothing the type names:
trim.tsts
let typedTask: string | undefined;if (typedTask !== undefined) { console.log(typedTask.trim());}
When TS18048 or TS18047 appears inside a check, read the last
word of the error: 'undefined' or 'null' is the nothing your
check let through. Then read the box's type, and check for the
nothing it names.
Pass all five tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
These run in your browser, so process.argv is not there to read:
where a value would come from the terminal, a box with no value
stands in for it, as in the examples above.
Exercise · Read the code
What is left in the else
Inside the else block, which type does typedTask have?
TypeScript refuses this program, and Node would stop on its first
question. Move the undefined question to the top, each question
together with the line under it, so the program prints
No command.
Loading the editor…
Exercise · Fix the error
Check for the right nothing
TypeScript refuses dueDate.toUpperCase(), although there is a
check in front of it. Change the check, and nothing else, so the
program prints No due date.
Loading the editor…
Exercise · Write the code
Lower case, or no command
No command was typed yet. Write an if with an else that prints
No command when command holds undefined, and Try: with the
command in lower case otherwise. Then put "ADD" in the box and
write the same if once more. The program prints two lines:
No command, then Try: add.
Loading the editor…
Exercise · Predict the result
The right side of &&
Which type does typedTask have where .trim() is called, on the
right of &&?
ts
let typedTask: string | undefined;const tidyTask = typedTask && typedTask.trim();
Recap
Recap · 3 questions
Check yourself
What does narrowing change?
Check yourself
In TaskKit's switch, which type does command have in default?
Check yourself
Why does !== null not help a string | undefined box?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Checking for null: a first look at narrowing
What things are
Word
What it means
Narrowing
A smaller type where a check protects the lines
Narrower type
One with fewer possible values: string
TS18048
Used as if there, but undefined is still possible
TS18047
The same, with null still possible
Code
Write
To
if (typedTask !== undefined) {
Inside, a string
if (typedTask === undefined) {
In its else, a string
if (dueDate !== null) {
Take null away
if (typedTask) {
Take every falsy value away, "" too
typedTask && typedTask.trim()
Right of &&, a string
case undefined:
Leave default only the strings
Rules
Rule
What it means
After the block
Each road's type joins: string | undefined again
One check, one nothing
!== null leaves undefined in
Chains carry it down
else if knows what the if took away
Filling counts too
= "Friday" tells TypeScript it is a string
Read the last word
'undefined' or 'null': what got through
Module 3 on one page
Cheat sheet
Module 3: Conditions and Missing Values
if / else and switch
Write or rule
What it means
if (added === limit) {
Ask, and open the block that depends on it
} else if (added > 0) {
Ask the next question
} else {
Open the block for every other answer
switch (command) {
Name the value to match
case "add":
Mark the lines for one exact value
break;
End a case
default:
Mark the lines for any other value
Logical operators, truthy and falsy values
Write or rule
What it means
task && added < limit
Both must be true: a task, and room
!task || full
One is enough: no task, or a full list
if (!full) {
Run the block when the answer is false
Six falsy values
false, 0, "", NaN, undefined, null
Guard first
typedTask && typedTask.trim(), never swapped
null and undefined
Write or rule
What it means
undefined
Nothing was put here; JavaScript gives it
null
Empty on purpose; a person writes it
string | undefined
A string, or nothing put there
process.argv.at(3)
Read a word that may not be typed
Optional chaining ?. and nullish coalescing ??
Write or rule
What it means
typedTask?.trim()
Trim it if it is there, else undefined
typedTask?.trim() ?? ""
A tidy task, or "" when none was typed
estimate ?? 15
15 only when the estimate is missing
?? keeps 0 and ""
They are values, not missing
Checking for null: a first look at narrowing
Write or rule
What it means
if (typedTask !== undefined) {
Inside, a string
if (dueDate !== null) {
Take null away
After the block
The roads' types join: the full type again
TS18048 / TS18047
Check for the nothing the error names
Where to go next
You can now check a box for undefined or null and say what
TypeScript knows about it on every line: the narrower type inside
the check, what is left in the else, and the type after the block,
where both roads join. You know which nothing each check takes away,
and TaskKit tells a person who typed ADD what went wrong. That
finishes Module 3: TaskKit chooses what to do, refuses what it
cannot use, and says why.
Next is Arrays and the T[] type, the first lesson of Module
4. So far TaskKit forgets every task as soon as it has printed
it. There you keep many values in one box, a list of tasks, and
read its type.
Before you move on, open index.ts and, for every line that names
command, say which type tsc gives it there. Then delete
case undefined once more and check that npx tsc agrees with you
about default. Put it back, run node index.ts Help and predict
which lines TaskKit prints.