Inference: when TypeScript knows the type and when to write it yourself
See how TypeScript works out a box’s type from its first value and from every operator and method, why a const box shows its value as a literal type while a let box shows the kind, and when writing the type yourself catches a first value of the wrong kind. Read every type in TaskKit on hover.
TypeScript
Fundamentals
Inference: when TypeScript knows the type and when to write it yourself. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In the last lesson you rested the pointer on minutes and VS Code
(Visual Studio Code, your editor) said const minutes: number.
Nobody wrote number on that line. Open TaskKit's index.ts and
count: ten boxes, and only one of them, added, has its type
written on it. TypeScript still knows the type of every one, and
checks every line against them.
Think of the checkout at a shop. You put a loaf and a carton of milk
on the counter, and nobody asks you which is which: the cashier
looks and knows. What the cashier asks is what looking cannot tell,
such as whether the loaf is a present. TypeScript works the same
way. By the end of this lesson you will read the type it works out
for any box, know why a const box shows its value while a let
box shows number, and write a type yourself in the places where
looking at the value is not enough.
TypeScript reads the right side
Lesson 2.2 showed it once: in let added = 0; there is no type, and
VS Code still shows let added: number when you rest the pointer on
the name, called hovering. TypeScript looked at the first value,
saw a number, and gave the box that type. Working a type out like
this, instead of being told, is called inference: TypeScript
infers the type.
It does not stop at plain values. In lesson 2.3 every operator gave
back one type: arithmetic a number, a comparison a boolean, a
template string a string. In lesson 2.4 every method did the same.
TypeScript knows those rules too, so it can take the right side of
any line apart and work out its type the way you would work out its
value, one operator at a time, before anything runs; Node never sees
any of it. Press Next step to follow it, or let it play:
total - done > 0
The right side of const busy = total - done > 0;, with
let total = 5; and let done = 2; above it. Nothing runs.
number - number > 0
Each name is read as the type of its box. Both boxes were
made with a number, so both are number.
number > number
A minus between two numbers gives a number, as lesson 3
showed. The - goes first, then the >.
boolean
A comparison answers with a boolean, so busy is a
boolean box: const busy: boolean on hover.
TypeScript works out the type the way you work out the value
All 4 steps shown.Step 1 of 4: total - done > 0Step 2 of 4: number - number > 0Step 3 of 4: number > numberStep 4 of 4: boolean
All 4 steps shown.
Here are those lines with two more, each built a different way:
infer.tsts
let total = 5;let done = 2;const busy = total - done > 0;const summary = `${done} of ${total}`;const tidy = " buy milk ".trim();console.log(busy, summary, tidy);
It prints true 2 of 5 buy milk. Running shows the values; the
types live in the editor. Copy the lines into a file in VS Code and
rest the pointer on each name: busy is a boolean, summary a
string, because a template string always gives text, and tidy a
string, because trim() gives back a new string. This is how
lesson 2.5's minutes got its type too: Number(text) always gives
back a number, so the box is a number box, even on the day the
number is NaN (not a number).
A const box gets its value as its type
Now rest the pointer on a const box and a let box. VS Code does
not say string for the first:
ts
const version = "0.1";// const version: "0.1"let added = 0;// let added: number
The const box shows its value, quotes and all, and the let box
shows the kind: one of the plain types of lesson 2.2, number,
which allows every number. Lesson 2.1 says why. A const box is
locked: it holds "0.1" from its line to the end of the program, so
TypeScript can say exactly which value is in it. The type "0.1"
allows one value, the text "0.1", and nothing else. A let box
can be refilled, so a type that allowed only 0 would refuse every
refill; TypeScript gives it the whole kind, number, instead. Here
are boxes like TaskKit's with the type each one gets:
A locked box is tagged with its value; a let box, with its kind
In Module 1 you met the string literal, text in quotes written
straight into the code. Any value written straight in is a
literal: "0.1", 5, false. A type that allows exactly one
such value is a literal type, and a const box filled
straight from a literal gets one. In Module 7 you will join
several literal types into one, to say that a task's status is
"todo" or "done" and nothing else. For now, read a literal
type as "this box holds this value, always".
A value worked out by an operator or a method does not do this. In
the flow above, busy is a const box and still shows boolean,
not true: its value comes out of a comparison, and TypeScript
works out the kind of that answer without running it.
Literal types also turn up in error messages, which is what lesson 2.4
left open. There, tidy.toUppercase() was refused because a
string has no toUppercase. Call it on lesson 2.4's task, made
with const task = " buy milk ";, and the same message says does not exist on type '" buy milk "'. That is the box's literal type.
Every literal type of text is a string, so read it as 'string'.
When to write the type yourself
Inference has one blind spot: it trusts your first value. It can
see what you wrote, never what you meant. Lesson 2.2's "0" counter
is this blind spot: without : number, "0" makes a string box and
nothing is caught; with : number, line 1 is refused. The type you
write is a promise about what the box is for, and TypeScript checks
the first value and every refill against it. Inference can only
describe what is already there.
That gives a short rule for every box you make:
Leave it to TypeScript when the value on the same line
already says the type: const room = limit - added;,
const tidy = task.trim();. Writing : number on room only
says it twice.
Write it yourself when the box is a let that later lines
keep refilling, so the first value is not the whole story.
TaskKit's added is one: it starts at 0, two lines refill it,
and without the type a slip on its first line, such as "0",
would only be reported far below, where room and percent are
worked out.
Write it yourself when the first value only stands in for
one you do not have yet. The common mistake below is that case.
In Module 5 you will meet the place where there is nothing to
infer from at all, the values a function receives, and there you
write every type.
What TypeScript decided for TaskKit
Open index.ts in ~/projects/taskkit and rest the pointer on
the name of every box, top to bottom. You change nothing in this
lesson; this is what VS Code shows:
VS Code shows
Worked out from
const version: "0.1"
A literal, in a locked box
const line: string
repeat() gives back a string
const limit: 5
A literal, in a locked box
let added: number
The type written on it
const tidyFirst: string
trim() gives back a string
const firstTask: string
String + string is a string
const tidySecond: string
trim() again
const secondTask: string
String + string again
const room: number
Number minus number
const percent: number
Math.round() gives a number
Nine of the ten types are worked out, and only added carries one
you wrote in lesson 2.2. It keeps it: it is the only box later lines
refill, and the type is what checks those refills.
Predict the type
left is filled from limit, whose type is 5. Decide what
VS Code shows for left before you read the answer.
Predict
What type does TypeScript give left?
ts
const limit = 5;let left = limit;left = left - 2;console.log(left);
The common mistake: a stand-in of another type
You want a box for the time estimate, but you do not have the number
yet: a person will type it later. So you make the box now with a
stand-in, a first value that only holds the place, here an empty
string, and fill it once the number arrives.
Common mistake
Starting a box with a stand-in of another type
npx tsc --noEmit index.ts (tsc is short for TypeScript
compiler) refuses line 2 with TS2322, TypeScript's code for
"this value does not fit this box", before anything runs:
index.tsts
let estimate = "";estimate = Number("25");console.log("Estimate:", estimate, "min");
You never wrote string anywhere, and the message talks about a
string box. TypeScript took the type from the first value, and
"" is text. Line 2 then tries to put a number into a box for
text.
Type 'number' is not assignable to type 'string'.
The fix
Start the box with a stand-in of the kind it is for, and write the
type, so the line says what the box will hold:
index.tsts
let estimate: number = 0;estimate = Number("25");console.log("Estimate:", estimate, "min");
When a message names a type you never wrote, rest the pointer on
the box it is about. The type came from the first value, and the
fix is usually on that first line, not on the line the message
names.
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. The first three ask you
to read types the way VS Code shows them, the fourth to fix a box
whose first value got its type wrong, and the last to apply the
rule.
Exercise · Read the code
What the hover shows
You rest the pointer on urgent in this line. What does VS Code
show?
ts
const urgent = false;
Exercise · Predict the result
A const filled from a question
What type does TypeScript give full? Type it the way it would
come after the colon on hover.
TypeScript refuses the last line with This comparison appears to be unintentional because the types '5' and '6' have no overlap.
Why?
ts
const limit = 5;console.log(limit === 6);
Exercise · Fix the error
Give the answer a boolean box
This program should print List full: true, but TypeScript
refuses it. Fix the line that makes the box, so the answer of the
comparison can go into it.
Loading the editor…
Exercise · Read the code
Which box is worth a written type
Which of these boxes is worth a type written by hand?
Recap
Recap · 3 questions
Check yourself
Where does the type of let added = 0; come from?
Check yourself
Why does const version = "0.1" show the type "0.1"?
Check yourself
When is writing the type yourself worth it?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Inference: when TypeScript knows the type
What things are
Word
What it means
Inference
TypeScript working out a type from the value
Literal
A value written straight into the code: "0.1", 5
Literal type
A type that allows one value: "0.1", 5
Hover
Resting the pointer on a name to see its type
Stand-in
A first value that only holds the place of a later one
What TypeScript works out
Write
Hover shows
let added = 0;
let added: number
const limit = 5;
const limit: 5
const version = "0.1";
const version: "0.1"
const room = limit - added;
const room: number
const full = added === limit;
const full: boolean
const tidy = task.trim();
const tidy: string
let estimate: number = 0;
let estimate: number, as written
Rules
Rule
What it means
The right side decides
No type written: the first value gives it
const and a literal
The type is the value itself
let
The whole kind, so the box can be refilled
Worked out
A value from an operator or method gets its kind
Yours wins
A type you write replaces what would be worked out
Leave it
The value on the line already says the type
Write it
The first value is not the whole story
Hover first
Read what TypeScript decided before you write
A type you never wrote
Look at the box's first value
Where to go next
You can now read the type TypeScript works out for any box, say
why a const box shows its value and a let box its kind,
recognise a literal type in an error message, and decide for each
box whether its type is worth writing. TaskKit's types are all
read, and the one written by hand is the one that earns its
place.
Next is Comments and names: writing code other people can
read. Types are one way a line tells a reader what it means; the
next lesson is about the other two, the names you give your boxes
and the notes you leave beside them.
Before you move on, see where the error lands without a type. In
index.ts, change let added: number = 0; to let added = "0";
and check the file: the messages name the lines that work out room
and percent, far below the mistake; all you need from them is that
a - or / needs numbers on both sides. Run it with node alone:
it prints room for -6 more and List 220% full, because - and
/ read the text "011" as the number 11. Then write : number
after added again, keep the quotes, and check once more: the
message now names line 9, where the mistake is. Take the quotes off,
and check and run it before you call it done.