Type errors vs runtime errors: why types vanish when the code runs
See the two kinds of error at their two moments: TypeScript’s while you type, Node’s while the program runs. Watch Node run a file TypeScript refused, with every type stripped out, and find the values no check can see, so you check them in code yourself.
Fundamentals
TypeScript
Type errors vs runtime errors: why types vanish when the code runs. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
Every message in the last lesson came from TypeScript, before a single
line ran. The one in this lesson appears only while the program runs.
In the morning you write a progress bar for a day of five tasks: tell
it how many you finished, and it prints [##---] 2 of 5 done. The
check prints nothing. During the day two more tasks join the list, and
by the evening you have done all seven. You type 7, but bar.ts still
says 5 tasks in all, and Node stops with RangeError: Invalid count value: -2. You check again, and the check still prints nothing.
Lesson 1.4 called TypeScript the proofreader and Node the printing
press. A proofreader reads every word on the page and marks every
mistake on it, but can only read what is on the page. The number
you type after node bar.ts is not on the page: it arrives when
the press is already running. In this lesson you learn to tell the
two kinds of error apart by when they appear, see what Node really
runs when it runs a .ts file, and find the values no check can
see, so that you check them yourself.
Two kinds of error, two moments
Lesson 1.5 taught you to tell from a message which tool wrote it,
TypeScript or Node. Now the two kinds get names, because almost every
error you meet is one of them. A type error is one TypeScript
finds by reading your code: a value that does not fit its type, a name
that was never made. VS Code (Visual Studio Code, your editor)
underlines it while you type, npx tsc (tsc is the TypeScript
compiler, which npx starts) prints it, and not one line has run.
Every message in the last lesson's catalogue was found this way, by
reading, before anything ran. Most of them are type errors, and Node
never looks at them. The few in the 1000s are about how the code is
written, not about types, and a missing quote or bracket among them
(TS1005, TS1002) stops Node too, with the SyntaxError of lesson
1.5.
A runtime error is one Node meets while the program runs, when
it reaches a line it cannot carry out. Runtime means exactly
that: the time while a program is running. You have met these too:
ReferenceError in lesson 1.4, TypeError: Cannot read properties of undefined in lessons 2.8, 4.1 and 5.8, and RangeError in
lesson 5.9. A runtime error stops the program on its line, and
everything above that line has already happened.
Here is the progress bar. It reads the count from process.argv[2]
(argv, short for argument vector, the list of words typed after
the command) and uses repeat, which builds TaskKit's banner line:
"#".repeat(3) gives "###". The bar is one # for each task done
and one - for each task left:
The code above is the finished version. The first time you write it,
you forget Number() on line 2, as lesson 2.8 warned you might, and
npx tsc --noEmit--types node bar.ts refuses line 3 before anything
runs: repeat is handed a string where it wants a number, with
TS2345 (TS for TypeScript, then the number of the message), and a
second message, TS2363, says the same of total - done. VS Code
cannot show this one yet: until Module 9 it keeps its red line under
process and reads it as any (lesson 2.8). Follow the file from
that first draft to the run that stops. Press Next step to walk
through it, or let it play:
You
TypeScript
Node
You: write bar.tswritebar.tswritebar.ts
TypeScript: TS2345TS2345TS2345
All 6 steps shown.Step 1 of 6: You: write bar.tsStep 2 of 6: TypeScript: TS2345Step 3 of 6: You: add Number()Step 4 of 6: TypeScript: checked ✓Step 5 of 6: You: node bar.ts 7Step 6 of 6: Node: RangeError
All 6 steps shown.
The runtime error came last, with one particular number, after the
check had said yes: repeat cannot repeat a text a negative number of
times, and 5 − 7 is -2. The rest of this lesson is about why the
check could not see it.
Types vanish when the code runs
Start with what Node does with your types. Lessons 2.2 and 7.6 said
that Node skips them: it runs in what lesson 7.6 called strip-only
mode. See what that means for a file with a mistake in it:
Save it in ~/projects/taskkit and check it:
It is the last lesson's message, with two lines broken here to fit the
page: TypeScript refuses the file. Now run it anyway, without fixing
anything:
No error, and no warning. Here is the file as Node runs it:
What you wrote
Does: TypeScript reads the types and refuses line 8
What Node runs
Does: Node never sees a type, and prints to do
Node runs your file with every type stripped out
Before the first line runs, Node strips every type out, leaving spaces
in its place: the type line, the four lines of interface Task, and
: Task after rent. What is left is plain JavaScript, and nothing
in it says that a status must be "todo" or "done". The spaces keep
every line in its place, which is why Node's errors name the same line
and column numbers as your file.
That is what the lesson's title means. Types exist while TypeScript
reads your code, and are gone when the code runs. They cannot stop
a wrong value at runtime, because at runtime there are no types.
Node does not refuse a file for a type error: the run goes on with
the wrong value inside, which can crash further on or, as here,
print a quiet wrong answer. status.ts was only for this test:
delete it.
TaskKit behaves the same. Make the change you made in the last
lesson, status: "to do" in the add case's tasks.push line,
save, and this time skip the check and run it:
The last line says [to do], a status Status does not allow,
printed as if nothing were wrong. Put "todo" back and check with the
command from the last lesson, npx tsc --noEmit--types node --allowImportingTsExtensions index.ts: it prints nothing. This is why
lesson 1.4 made you check before every run.
What the check cannot see
bar.ts has no type error at all, and still stopped. Why did
TypeScript not see it coming? Because it never sees the 7. TypeScript
reads bar.ts once, before it runs, and at that moment nobody has
typed anything. All it knows about done is its type, number, as
lesson 2.5 found for Number("ten"), and repeat takes a number.
Every line fits.
Save bar.ts in ~/projects/taskkit, with Number(), and run it
three ways:
The check prints nothing. For node bar.ts 7, Node prints the line it
stopped on with a ^ under the second repeat, then RangeError: Invalid count value: -2 and the at … lines of lesson 5.9: first at String.repeat, inside JavaScript's own code, then your own line,
bar.ts:3:36, and below it only Node's own code. What each run does:
npx tsc saysnode printsTyped 2
Printsnothing
Every value fits its type
[##---]2of5done
The bar you wanted
Typed 7
Printsnothing
The same check
Range
What decides each run arrives only while the program runs: the words
typed after node bar.ts, how many tasks a list holds at that moment,
and later in the course what a file or a website sends back.
TypeScript cannot read what does not exist yet. The third run did not
even stop. With nothing typed, process.argv[2] is undefined, and
Number(undefined) gave NaN, as lesson 3.3 showed, and the bar
quietly came out empty: a mistake at runtime does not always stop the
program.
Sometimes a type tells the truth about what may happen at runtime, and
then TypeScript does see it. In lesson 4.1, tasks[3] was typed
string although it held undefined. .at() tells the truth: its
type is string | undefined, and so is find's. That is why TaskKit
reads its command with process.argv.at(2). A type that says | undefined moves the mistake from the run to the check: TypeScript
makes you handle the missing value before anything runs. But
Number() can only promise a number, never which one, so checking
that it is between 0 and 5 is your job.
Predict what Node prints
TypeScript refuses this file with Type 'string' is not assignable to type 'number'. on line 5. You run it with node call.ts anyway,
without fixing it.
Predict
What does node call.ts print?
The common mistake: trusting a clean check
A check that prints nothing feels like a promise that the program
works. It promises less than that.
Common mistake
Treating a clean check as proof that the program works
You saw this run in the table: the check said nothing, and 7 stopped
it. Here it is on the page:
Press Run: the check passes, and the run stops on line 5.
RangeError: Invalid count value: -2
The fix
Check the number in your code before you use it, and say what went
wrong when it does not fit:
Now it prints Done must be 0 to 5. Change typed to "2" and to
"ten", and run it each time: "ten" becomes NaN, which is neither
>= 0 nor <= 5, so it gets the message too. A clean check means
that every value fits its type, and nothing more. Every value that
comes from outside your code gets a check in code before you use it. A
message is one way to answer a bad value; the next lesson shows
another.
Pass all three 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; if you are stuck, the hints come one at a time.
Recap
Recap · 3 questions
Check yourself
When does a runtime error appear?
Check yourself
What does Node run when you run a .ts file?
Check yourself
Why can TypeScript warn you that find may find no task?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Type errors vs runtime errors
What things are
Word
What it means
Type error
TypeScript's, found by reading the code
Runtime error
Node's, found at the line while it runs
Runtime
The time while a program is running
What Node runs
Your file with every type stripped out, leaving spaces
When each one appears
Moment
What you see
While you type
A red line in VS Code: a type error
npx tsc --noEmit
Every type error, before any line runs
node file.ts
It runs, even a file with type errors
While it runs
A runtime error, when Node reaches the line
Rules
Rule
What it means
Types vanish
Nothing stops a wrong value once the code runs
Check first
Node never refuses a file for its types
A clean check
Every value fits its type, nothing more
| undefined
A truthful type moves a runtime error to the check
Values from outside
Check them with if before you use them
Where to go next
You can now tell a type error from a runtime error by when it
appears, explain why Node runs a file TypeScript refused, and spot
the values only a run can show, so that you check them in code.
Next is throw and try / catch. In this lesson a bad value
either stopped the program with Node's own error or met your if.
That lesson shows how your code raises an error of its own, and how a
program catches one and carries on. The lesson after it, Where to
throw and where to catch: friendly errors for bad commands, then
uses both to give TaskKit friendly messages for bad commands.
Before you move on, put the fix into your own bar.ts: the if and
else around the last two lines, with Number(process.argv[2]) still
on line 2. Run it with 0, 5, -1 and 3.5, and before each run
say which you expect: the bar, the message, or a quiet wrong answer.
Then look at what 3.5 printed, and decide whether your check should
let it in, and how lesson 2.5's Math.round could tell.
You: add Number()
addNumber()addNumber()
TypeScript: checked ✓checked✓checked✓
You: node bar.ts 7nodebar.ts7nodebar.ts7
Node: RangeErrorRangeErrorRangeError
Time
You type the progress bar, with no Number() on line 2, and
check it.
The check, before anything runs: on line 3, repeat wants a
number and gets a string. Nothing has run.
You wrap the typed word in Number(), save and check
again.
npx tsc finds nothing: every value fits its type.
You run it and say that 7 tasks are done, out of 5.
While it runs: done holds 7, so the second repeat gets -2,
and Node stops on line 3.
A type error shows up before the program runs, while you
type or when you check; a runtime error only while it runs
Error
The second repeat gets -2, and the run stops on line 3
Nothing typed
Printsnothing
The same check
[]NaNof5done
No error, and a wrong answer: NaN, short for not a number
node bar.ts three ways: one check for all three, three
different runs
Exercise · Read the code
Which one only a run can show
Each line below comes from a file where everything else is right.
Which mistake can TypeScript not find before the program runs?
Exercise · Predict the result
A run that does not stop
npx tsc --noEmit--types node progress.ts prints nothing. You run
node progress.ts ten. What is the last line it prints?
Outputtext
status.ts:8:3 - error TS2820: Type '"to do"' is notassignable to type 'Status'. Did you mean '"todo"'?8 status: "to do", ~~~~~~ status.ts:4:3 - The expected type comes from property 'status' which is declared here on type 'Task' 4 status: Status; ~~~~~~Found 1 error in status.ts:8
Outputtext
to do
Outputtext
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentTasks added: 1 of 5, room for 4 moreList 20% fullYour list, A to Z:#1 [to do] Pay rent, due: not set
bar.tsts
const total = 5;const done = Number(process.argv[2]);const bar = "#".repeat(done) + "-".repeat(total - done);console.log(`[${bar}] ${done} of ${total} done`);
// What process.argv[2] holds after: node bar.ts 7const typed = "7";const total = 5;const done = Number(typed);const bar = "#".repeat(done) + "-".repeat(total - done);console.log(`[${bar}] ${done} of ${total} done`);
bar.tsts
// What process.argv[2] holds after: node bar.ts 7const typed = "7";const total = 5;const done = Number(typed);if (done >= 0 && done <= total) { const bar = "#".repeat(done) + "-".repeat(total - done); console.log(`[${bar}] ${done} of ${total} done`);} else { console.log(`Done must be 0 to ${total}`);}
Exercise · Fix the error
Let the type admit a missing task
nextTask looks a task up by the number typed for it. TypeScript
accepts the program, and the run stops on the second call, because
there is no task 7 (task 3 was done and taken off the list). Find the
task by its id (short for identifier, the number that names one
task) with a method whose type admits that it may find nothing, and
give back No task #7, with the typed number, for any number that is
no task's id.