Work out new numbers with + - * / and %, and know which goes first. Ask questions with === and < that answer true or false, and see why + joins text instead of adding. Put values into text with template strings, read TS2367, and make TaskKit say how much room is left.
TypeScript
Fundamentals
Arithmetic, comparisons, and template strings. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
At the end of the last lesson TaskKit's counter got its type,
number, and the program printed Tasks added: 2. That is all it
can do with its values so far: keep them in boxes and print them
back. Ask it anything more, such as how many more tasks fit on
today's list, or whether the list is full, and it has no way to
answer.
Look at a receipt from a shop. It adds up the prices. It checks
one thing: is the total over the amount that gets you free
delivery? And it writes sentences with the numbers dropped into
them: "You saved 3.20 today." Adding, asking, and writing values
into text are three different jobs, and TypeScript has a tool for
each. By the end of this lesson you will work out new values from
the ones you have, ask questions whose answer is true or
false, and build a sentence with values inside it. TaskKit will
tell you how much room is left on today's list.
Three jobs, three kinds of answer
Everything in this lesson is an expression: a piece of code
that works out to one value. 5 is an expression, so is total,
and so is total - done. Most expressions are built with an
operator, a symbol such as - that takes the values on either
side of it and gives back a new one.
These expressions come in three kinds. Arithmetic gives back a
number, a comparison a boolean, a template string a string,
and TypeScript knows which before anything runs. One operator breaks
the pattern: + with text gives back a string, and it has a section
of its own. Two signs in the figure, % and the backticks with
${}, are explained in their own sections below:
With done = 2 and total = 5: each kind gives back one type
Two slashes, //, start a comment: a note for people. The
computer skips everything from // to the end of the line. Here
each comment says what the expression gives, the way the examples on
MDN (Mozilla's JavaScript documentation) do. The rest of this lesson
takes the three kinds one at a time.
Arithmetic: numbers in, a number out
Five operators do arithmetic. Four are the ones from school:
+ adds, - subtracts, * multiplies, and / divides. The
fifth, %, gives the remainder: what is left over after
dividing into whole groups. Seven tasks shared out in pairs make
three pairs and leave one task over, so 7 % 2 is 1. Run them:
Each line prints one number: 10, 4, 14, 3.5 and 1.
Dividing 7 by 2 gives 3.5, not 3: a whole number and a decimal
are the same type, number, so the answer keeps its half.
When one expression holds several operators, they are not always
worked out from left to right. As in school, *, / and % go
before + and -, and anything in parentheses goes before
everything else:
The first line works out 2 * 3 first and prints 4. The second
does the subtraction first, because of the parentheses, and
prints 24. When you are unsure which goes first, add
parentheses: they cost nothing and the next reader does not have
to work it out either.
-, *, / and % only take numbers, and TypeScript refuses a
string on either side of them before anything runs. + is
different, and it is the next section.
The same + joins text
+ has a second job. Between two strings it joins them into one:
"Buy " + "milk" is "Buy milk". Joining strings like this is
called concatenation. When one side is a string and the other
a number, + turns the number into text and joins the two. That
is where the last lesson's 011 came from: "0" + 1 is "01".
An expression with several + signs is worked out one + at a
time, from left to right, and each one sees the result of the one
before it. Press Next step to follow it, or let it play:
"Tasks: " + 2 + 3
"Tasks: " + done + left, with 2 in done and 3 in left.
The left + goes first, and its left side is text.
"Tasks: 2" + 3
Text plus a number is text, so the 2 is glued on, not added.
One + is left, and its left side is text again.
"Tasks: 23"
The 3 is glued on too. Nothing was ever added, and no error
tells you so.
Two + signs, left to right: the text comes first, so both glue
All 3 steps shown.Step 1 of 3: "Tasks: " + 2 + 3Step 2 of 3: "Tasks: 2" + 3Step 3 of 3: "Tasks: 23"
All 3 steps shown.
Run both lines. In the second, parentheses make the numbers meet
first:
The first line prints Tasks: 23, the second Tasks: 5. Inside
the parentheses both sides are numbers, so + adds; only then is
the 5 joined to the text. TypeScript says nothing about the first
line, because joining text and numbers is allowed: it is often
exactly what you want. Parentheses fix it here, and the section on
template strings shows a way of building text where the question
never comes up.
Comparisons: a yes-or-no question
A comparison asks a question about two values and answers
with a boolean: true or false. Is the list full? Are there
tasks left? Six operators ask six questions. In the examples
added has been counted up to 2 and limit holds 5:
Operator
Asks
With 2 and 5
===
Are they equal?
added === limit is false
!==
Are they different?
added !== limit is true
<
Is the left one smaller?
added < limit is true
>
Is the left one bigger?
added > limit is false
<=
Smaller, or equal?
added <= limit is true
>=
Bigger, or equal?
added >= limit is false
The answer is a value like any other, so it can go in a box. A
box filled by a comparison is a boolean box:
It prints false, true, and List full: false. For now the
answers are only printed. In the next module they decide which
lines of a program run at all.
Notice the three equals signs. One = is the order you met two
lessons ago: work out the right side and put it in the box. It
never asks anything. === asks whether two values are equal and
changes nothing. Two strings are equal only when every character
matches, capital letters and spaces included, and a value of one type is
never equal to a value of another: the string "2" is not the
number 2. That last rule is behind the common mistake at the
end of this lesson.
Template strings: values inside text
You have built lines of output in two ways so far. Commas in
console.log put a space between values, always, so they cannot
print 2/5 or (2 of 5). + can, but you saw what it joins when
the numbers come after the text. A template string is a third
way, made for exactly this job: text with values written straight
into it.
A template string is written between backticks, `, instead
of double quotes. On American and British PC keyboards it is the key
to the left of 1; on a Mac with a British layout, the key to the
left of Z. On some layouts the key waits for the next one: press it,
then Space. Inside a template string, ${ and } mark a
placeholder: the expression between them is worked out, and its
value takes its place in the text.
summary.tsts
const done = 2;const total = 5;console.log(`Done: ${done} of ${total}`);console.log(`Left: ${total - done}`);console.log(`Progress: ${done}/${total}`);
It prints Done: 2 of 5, Left: 3 and Progress: 2/5. Any
expression can go in a placeholder, arithmetic included: in
${total - done} the subtraction happens first, and its answer
is put in the text. The question of what + does never comes up,
because every value lands exactly where you wrote it, with the
spaces you typed around it and no others. A template string is a
string, so it can go in a box too:
const summary = `${done} of ${total}`;.
The backticks are the whole trick, and they are easy to miss.
Bad — double quotes, so ${done}
is only characters in the text.
ts
const done = 2;console.log("Done: ${done}");
Good — backticks, so ${done}
is a placeholder and the 2 goes in.
ts
const done = 2;console.log(`Done: ${done}`);
Run both. The first prints Done: ${done}, dollar sign and
braces and all, and nothing warns you: to TypeScript it is an
ordinary string that happens to contain those characters. Text
like that reaches the screen of whoever runs your program. When a
placeholder shows up in the output, look at the first character
of the string.
TaskKit says how much room is left
A short list gets done; a long one gets copied to tomorrow. Give
TaskKit a daily limit of five tasks, and let it say how many more
fit. Open index.ts in ~/projects/taskkit and make two
changes: add the limit box above added, and replace the last
line with a room box and a template string. The lines marked
+ are new, and the one marked - goes:
index.tsts
const version = "0.1";const line = "=".repeat(28);console.log(line);console.log("TaskKit", version);console.log("Your tasks, in your terminal");console.log(line);const limit = 5;let added: number = 0;const firstTask = "Buy milk";console.log("Added:", firstTask);added = added + 1;const secondTask = "Call the dentist";console.log("Added:", secondTask);added = added + 1;console.log("Tasks added:", added);const room = limit - added;console.log( `Tasks added: ${added} of ${limit}, room for ${room} more`);
The console.log is spread over three lines because the template
string is long; a line break between the parentheses changes
nothing. limit and room are const: neither is refilled.
Check the file with tsc (short for TypeScript compiler), then
run it:
bash
npx tsc --noEmit index.tsnode index.ts
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Buy milkAdded: Call the dentistTasks added: 2 of 5, room for 3 more
The last line is new, and every value in it was worked out by the
program: room by arithmetic, and the sentence by a template
string. Add a third task the same way as the first two, and the
line changes by itself to 3 of 5, room for 2 more.
Predict before you run
The figure above showed + with the text first. Turn the
expression around, so the numbers come first, and decide what
happens before you run it.
Predict
What is the first line this program prints?
ts
const done = 2;const left = 3;console.log(done + left + " tasks");console.log("Tasks: " + done + left);
The common mistake: a string against a number
TaskKit's version is in a box: const version = "0.1";. You
want a line that says whether this is the first release, so you
compare the version with what you see on the screen, 0.1. But the
box holds the string "0.1", and 0.1 without quotes is a number.
Common mistake
Comparing a string with a number
The file:
index.tsts
const version = "0.1";const firstRelease = version === 0.1;console.log("First release:", firstRelease);
npx tsc --noEmit index.ts refuses line 2 with TS2367,
TypeScript's code for this error: a
string and a number can never be equal, so the question
always has the same answer, and TypeScript guesses you did not
mean to ask it.
This comparison appears to be unintentional because the types 'string' and 'number' have no overlap.
The fix
Compare like with like. The version is a string, so ask about the
string "0.1", in quotes:
index.tsts
const version = "0.1";const firstRelease = version === "0.1";console.log("First release:", firstRelease);
What happens next depends on whether anything checks the file
first. Press Next step to follow it, or let it play, and switch
between the two ways of running it:
Line 2 asks version === 0.1: the string "0.1" against the
number 0.1.
This comparison appears to be unintentional because the types 'string' and 'number' have no overlap. Nothing runs.
The check failed, so you fix line 2 before you run anything.
Nothing reaches the screen.
A string against a number: caught before running, or a quiet false
All 4 steps shown.Step 1 of 4: Your code: index.tsStep 2 of 4: TypeScript: TS2367Step 3 of 4: Node: never startsStep 4 of 4: Screen: nothing printed
All 4 steps shown.
Yourcode
TypeScript
Node
Screen
Your code: index.tsindex.tsindex.ts
TypeScript: never askedneveraskedneverasked
Node: lines 1–3lines1–3lines1–3
Screen: First release: falseFirstrelease:falseFirstrelease:false
Time
Line 2 asks version === 0.1: the string "0.1" against the
number 0.1.
You ran node index.ts straight away, so nothing checked the
file.
=== compares the types too. A string never equals a number,
so the answer is false.
No error at all: version 0.1 is the first release, and the
program says it is not.
A string against a number: caught before running, or a quiet false
All 4 steps shown.Step 1 of 4: Your code: index.tsStep 2 of 4: TypeScript: never askedStep 3 of 4: Node: lines 1–3Step 4 of 4: Screen: First release: false
All 4 steps shown.
This is the third mistake in this module that the check catches and
a run alone does not, and the quietest. A refilled const crashed
halfway; a number in quotes printed 011, which at least looks odd.
Here the program prints false, a perfectly believable answer, and
it is wrong.
When you see TS2367, the two types in the message are the two
sides of your comparison. Look at the line it names and decide
which side has the type you meant, then change the other one. It
prints First release: true once both sides are strings.
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. The first two ask you
to read code, the last two to change and write it.
Exercise · Predict the result
Work out the order
What is in the box left once this line has run? Answer with a
number.
ts
const left = 12 - 6 / 2;
Exercise · Read the code
Ask, do not fill
Which line puts the answer to "is added equal to limit?" into
the box full?
Exercise · Fix the error
Count before you join
This program should print Today: 6 and then Morning: 2. It
runs, but both lines come out wrong. Fix them without changing the
first two lines.
Loading the editor…
Exercise · Write the code
Write TaskKit's summary
TaskKit's limit is 5, and three tasks have been added. Make two
more boxes:
room, how many more tasks fit, worked out from limit and
added;
full, whether added has reached limit, as a boolean.
Then print these two lines, with template strings:
text
Tasks added: 3 of 5Room for 2 more. List full: false
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What type of value does added < limit give?
Check yourself
What does "Tasks: " + (2 + 3) give?
Check yourself
Which line prints Done: 2 when done holds 2?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Arithmetic, comparisons, and template strings
What things are
Word
What it means
Expression
Code that works out to one value
Operator
A symbol that makes a new value, like - or ===
Remainder
What % leaves after whole groups: 7 % 2 is 1
Concatenation
Joining strings with +
Comparison
A question about two values, answered with a boolean
Template string
Text in backticks, with values in ${}
Placeholder
${} in a template string: its value goes in
Code
Write
To
limit - added
Work out a number: also +, *, /, %
(10 - 2) * 3
Make the part in parentheses go first
added += 1;
Refill: the same as added = added + 1;
added === limit
Ask whether two values are equal
added !== limit
Ask whether two values differ
added < limit
Ask which is smaller: also >, <=, >=
`${done} of ${total}`
Build text with values inside it
Rules
Rule
What it means
* before +
*, /, % go first; parentheses before all
Text joins
"Tasks: " + 2 is "Tasks: 2", never a sum
Left to right
Each + sees the result of the one before it
= and ===
One fills a box; three ask a question
=== keeps types
A string never equals a number
TS2367
The two sides of a comparison have different types
==
Older code: equal after converting types; never write it
Backticks only
In double quotes, ${done} prints as it is
Where to go next
You can now work out new values with arithmetic and say which
operator goes first, ask questions that answer true or false,
and put values into text with a template string, without +
joining numbers you meant to add. TaskKit tells you how much room
is left on today's list.
Next is Working with strings: common methods. Template
strings build text; the next lesson takes text apart and changes
it: how long it is, whether it contains a word, and how to make a
task name tidy before TaskKit prints it.
Before you move on, make the backtick mistake on purpose. In
index.ts, change the backticks around TaskKit's summary to
double quotes, run it with node, and read the last line it
prints. Put the backticks back, check the file, and run it once
more before you call it done.