Use a value that may be missing with ?., which goes round null and undefined instead of calling a method on them, and give the line a default with ??. See why ?? keeps a real 0 that || replaces, and make TaskKit read, tidy and default its task in one line.
Fundamentals
TypeScript
Optional chaining `?.` and nullish coalescing `??`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson TaskKit's type for the task started
telling the truth: process.argv.at(3) says string | undefined,
and tsc (short for TypeScript compiler, the checker npx
starts) refuses any line that uses the task before checking it. Now
read the add case once more. Just to tidy the task, it names
typedTask three times:
if (typedTask && typedTask.trim() !== ""), then
const tidyTask = typedTask.trim();.
Picture a road with a sign on it: Bridge closed. Detour. The sign
does not end your trip, and it does not send you into the river. It
takes you round the gap and back onto a road that goes on.
JavaScript has an operator that works like that sign, ?., and one
that works like the road you come back to, ??. By the end of this
lesson TaskKit reads its task in one line, and you know why the ||
default from lesson 2 of this module turns a real 0 into a wrong
answer.
Use a value only if it is there
You have met the same problem three times now. .trim() on a box
that holds undefined stops the program with a TypeError.
Module 2's lesson 8 saw it happen, lesson 2 of this module put a
guard in front of it, and the last lesson made tsc insist on the
guard. The guard works. It is also the same words every time:
name the box, ask whether it holds something, name it again, and
only then call the method.
Optional chaining, written ?., is that guard in two
characters. typedTask.trim() calls .trim() on whatever the box
holds. typedTask?.trim() looks in the box first: if it holds
undefined or null, the rest of the chain is skipped and it gives
back undefined, and .trim() is never called. If it holds a
string, .trim() runs as usual. The name comes from Module 2's
lesson 4, where methods joined by dots made a chain (chaining): ?.
is a link in that chain that is allowed to find nothing.
Here is TaskKit's line, with typedTask read by
process.argv.at(3), written three ways:
. (a dot)
Does: Calls .trim() on whatever the box holds
Never: Never passes the check: the box may hold undefined
&& (a guard)
Does: Checks first, then calls .trim()
Never: Never says it once: the box is named twice
?. (optional chaining)
Does: Calls .trim() only when there is a value
Never: Never calls it on undefined or null
?. checks first, like the && guard, and names the box once
The second and third lines do the same work: both check first, and
both give back undefined when nothing was typed. The third says
it once, and tsc accepts it, because ?. is exactly the check it
was asking for.
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 a
box with no value: a let with a type and no =. Until a line
fills it, it holds undefined, just as typedTask does after
node index.ts add. Run it:
It prints undefined, then buy milk. The first ?. found
nothing and went round .trim(); the second found a string and
called it. Here is the detour drawn out, for the line TaskKit will
use by the end of this lesson. Its last part, ?? "", is two
sections away: for now, read it as "or, if nothing came out, the
empty string". Choose what was typed after add on the tabs, then
press Next step to follow the line, or let it play:
You only need ?. where the type says the box may be empty: on a
string it does nothing special.
One ?. guards the rest of the chain
When ?. finds nothing, it does not skip only the method right
after it. It skips the rest of the chain, every . after it. That
is what you want: once there is no task, there is nothing to trim,
and nothing to turn into capitals either.
It prints undefined twice, then BUY MILK and 10. The
.toUpperCase() needs no ?. of its own: if the chain gets that
far, .trim() has already given back a real string. And ?. works
before a property as well as a method: typedTask?.length is the
number of characters, or undefined when no task was typed.
Now look at the type. In VS Code (Visual Studio Code, your editor)
make a new file, shout.ts, with
let typedTask: string | undefined; and
const shout = typedTask?.trim().toUpperCase();, and hover over
shout: it says const shout: string | undefined. (Hovering over
typedTask in index.ts still shows any, as Module 2's lesson 8
warned; the terminal check is the judge.) ?. does not make the
nothing go away. It carries it safely to the end of the chain, where
it is still waiting for whoever uses the result.
??: a value to use when there is nothing
Often undefined at the end of the line is not what you want. You
want something to carry on with: an empty task, "no date", 15
minutes. Lesson 2 of this module did that with ||. JavaScript has
an operator made for it.
Nullish coalescing, written ??, gives back its left side,
unless that side is null or undefined; then it gives back its
right side. Those two values have a name of their own: they are
nullish, the two kinds of nothing. Read typedTask ?? "" as
"typedTask, or, if it is nothing, """. (Coalescing means
joining into one: two possible values come out as one.)
It prints Task: "". Copy default.ts into a VS Code file and
hover over tidyTask: the type is plain string. Whatever the left
side gave, the box gets a string, so every later line can call
.slice() on it without checking it first. ?. goes round the
missing value; ?? brings the line back onto a road you chose.
?? or ||: which values count as missing
Lesson 2 of this module already gave you a default:
typedName || "friend". It works because || gives back its right
side whenever the left one is falsy. The catch is the word falsy.
There are six falsy values from lesson 2 of this module, false,
0, "", NaN (short for not a number), null and undefined,
and only two of them mean "nothing here". Press Next part to
walk through the two groups, or let it play:
Falsy
false, 0, "", NaN, null, undefined
Nullish
null, undefined
??
every value of the second is also in the first
?? replaces only null and undefined, two of the six falsy values
All 3 parts shown.Part 1 of 3: Falsy: false, 0, "", NaN, null, undefinedPart 2 of 3: Nullish: null, undefinedPart 3 of 3: ??: every value of the second is also in the first
All 3 parts shown.
|| replaces everything in the big circle, ?? only what is in the
small one. For a word typed by a person that rarely matters. For a
number it decides whether the answer is right. A task's estimate in
minutes may be null because the person chose to give none, or a
real 0 because the task is already done. A box like that has the
type number | null, the string | null of the last lesson with a
number in it.
Bad — || reads the real 0 as
missing and replaces it.
Good — ?? replaces only null
and undefined, so 0 stays 0.
The first prints About 15 minutes for a task that takes none,
with no error and no warning, and every total built on it is
quietly wrong. The second prints About 0 minutes. Use ?? when
0 or "" can be a real answer; keep || for the rare default
where every falsy value should be replaced, such as a name that
must not be blank.
TaskKit reads its task in one line
Now TaskKit's step for this lesson. Open index.ts in
~/projects/taskkit. Replace the line that reads the task with
one that reads it, tidies it and gives it a default, and ask the
if one question about the result:
Read the new line from left to right: take the word after add;
if there is one, trim it; if there was none, use "". Whatever
you type, tidyTask is a string, so the if asks a single
question, "is there anything left?", and the box typedTask is
gone. The else with its hint, the help case, case undefined
and everything below the switch stay as they were.
Check the file, then run TaskKit the three ways that matter:
npx tsc prints nothing: the file passes. The first run prints
what it printed before:
The other two both print the hint:
They get there by different roads. Three spaces are a string, so
?. goes on, .trim() gives back "", and ?? keeps it, because
"" is not nullish. No word at all is undefined, so ?. goes
round .trim() and ?? fills in "". Either way the if sees an
empty string. The guard you wrote in lesson 2 of this module is
gone, and nothing in TaskKit can call .trim() on nothing.
Predict before you run
The line below asks for the length of the trimmed task, and no task
was typed. Decide where the chain stops, then what is printed.
Predict
What does this program print?
The common mistake: ?. with no default
?. makes a line safe, and it is easy to believe it makes the
value safe too. It does not: the nothing it found comes out at
the end of the line.
Common mistake
Using the result of ?. as if it were always there
You tidy the task with ?., so .trim() can never fail, and then
use what it gave back:
npx tsc --noEmit tidy.ts refuses line 3 with TS18048. Line 2
is safe, but when there is no task it hands its undefined on to
tidyTask, whose type is string | undefined. Run it with Node
alone and line 3 stops with TypeError: Cannot read properties of undefined (reading 'toUpperCase').
'tidyTask' is possibly 'undefined'.
The fix
End the line with ?? and the value to use when there is nothing:
It prints NO TASK, and tidyTask is a string.
When TS18048 names a box made from a line with ?., look at the
end of that line: the undefined comes from there. Give the line a
default with ??, or check the box before you use it, as the next
lesson shows.
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.
Recap
Recap · 3 questions
Check yourself
typedTask holds undefined. What does typedTask?.trim() do?
Check yourself
Which values does ?? replace with its right side?
Check yourself
Why does TaskKit end its line with ?? ""?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Optional chaining ?. and nullish coalescing ??
What things are
Word
What it means
?.
Optional chaining: go on only if there is a value
??
Nullish coalescing: the left side, or the right if nothing
Nullish
null or undefined, the two kinds of nothing
Falsy
The six values a condition reads as false
Code
Write
To
typedTask?.trim()
Trim it if it is there, else undefined
typedTask?.length
Its length, or undefined
?.trim().toUpperCase()
One ?. guards the rest of the chain
typedTask?.trim() ?? ""
A tidy task, or "" when none was typed
estimate ?? 15
15 only when the estimate is missing
(name || saved) ?? ""
Mix ?? with || or && in parentheses
Rules
Rule
What it means
?. keeps the nothing
Its result is string | undefined
?? ends it
x?.trim() ?? "" is a string
?? keeps 0 and ""
They are values, not missing
|| replaces all falsy
0 || 15 gives 15
on
Where to go next
You can now use a value that may be missing with ?., which goes
round null and undefined instead of calling a method on them,
and give the line a value to fall back on with ??. You know that
?? replaces only the nullish values, while || replaces all six
falsy ones, and TaskKit reads, tidies and defaults its task in one
line.
Next is Checking for null: a first look at narrowing. In the
last lesson tsc refused typedTask.trim() on a box of
string | undefined, then accepted the same call once
typedTask && stood in front of it. There you see how TypeScript
follows your checks and narrows a type, line by line.
Before you move on, run node index.ts add and
node index.ts add " " once more, and for each one say which
road the line took: did ?. go round .trim(), and did ?? fill
in the ""? Then change the default to "(nothing)", predict what
each run prints now, run them, and put the "" back.
typedTask
?.
.trim()
??""
typedTask: "buy milk""buymilk""buymilk"
?.: a string: go onastring:goonastring:goon
.trim(): "buy milk""buymilk""buymilk"
?? "": "buy milk""buymilk""buymilk"
Time
The word typed after add: a string.
?. finds a string, so the line goes on to .trim().
.trim() runs on the string and gives back a tidy copy.
A string is not missing, so ?? keeps it as it is.
With no task, ?. goes round .trim(), and ?? fills in ""
All 4 steps shown.Step 1 of 4: typedTask: "buy milk"Step 2 of 4: ?.: a string: go onStep 3 of 4: .trim(): "buy milk"Step 4 of 4: ?? "": "buy milk"
All 4 steps shown.
typedTask
?.
.trim()
??""
typedTask: undefinedundefinedundefined
?.: undefined: stopundefined:stopundefined:stop
.trim(): never callednevercallednevercalled
?? "": """"""
Time
Nothing was typed after add, so .at(3) gives undefined.
?. finds undefined, stops there and gives undefined.
.trim() is never called on nothing, so no TypeError.
The left side is undefined, so ?? gives "" instead.
With no task, ?. goes round .trim(), and ?? fills in ""
All 4 steps shown.Step 1 of 4: typedTask: undefinedStep 2 of 4: ?.: undefined: stopStep 3 of 4: .trim(): never calledStep 4 of 4: ?? "": ""
All 4 steps shown.
?.
null
Gives undefined, not null
TS18048 after ?.
End the line with ?? and a default
TS5076
Put parentheses round the || part
Exercise · Read the code
Where the detour leads
The person took the due date off, so dueDate holds null. What
does dueDate?.trim() give back?
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkTasks added: 1 of 5, room for 4 moreList 20% full
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Add what? Try: node index.ts add "buy milk"Tasks added: 0 of 5, room for 5 moreList 0% full
let typedTask: string | undefined;const tidyTask = typedTask?.trim();console.log(tidyTask.toUpperCase());
tidy.tsts
let typedTask: string | undefined;const tidyTask = typedTask?.trim() ?? "no task";console.log(tidyTask.toUpperCase());
Exercise · Fix the error
Give the due date a default
TypeScript refuses this program. Change line 3, and nothing else,
so it prints Due: NONE when no due date has been set.
Loading the editor…
Exercise · Fix the error
Keep the real zero
You want no break at all, so the break is 0 minutes, but this
program prints Pause: 5 minutes. Change one operator so it prints
Pause: 0 minutes, while a null break would still give 5.
Loading the editor…
Exercise · Write the code
A note that may not be written
No note has been written yet. Print it in capitals with ?., and
use ?? to print none when there is no note. Then put
"call ana" in the box and print it again the same way. The program
prints two lines: Note: none, then Note: CALL ANA.