Meet the two types that take any value and work as opposites: any switches TypeScript’s checks off, while unknown keeps them on until a check says what the value is. Open an unknown with typeof and instanceof, choose the type that keeps TypeScript checking, and give TaskKit’s catch a sentence for anything it catches.
Fundamentals
TypeScript
`any` vs `unknown`: the escape hatch and the safe box. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In lesson 8.3 TypeScript refused error.message inside a catch,
with 'error' is of type 'unknown'., and you checked the value with
instanceof before you read it. Search the web for that message,
and one of the first answers says: write catch (error: any). You
try it, and the red line is gone.
Both words mean "a value of any type", and they work as opposites.
any is an escape hatch, an emergency way out: it gets you
out of the error, and out of every check TypeScript would make on that
value from then on. unknown is a safe box: anything can go
in, but nothing comes out until a check says what it is. By the end of
this lesson you will know which one you are holding, open an unknown
with checks you already know, and TaskKit's catch will have a
sentence for anything it catches.
Two types that take anything
A type says which values fit in a box, and for these two the answer is
every value. A box made with let note: any takes "Pay rent" and
later 7, and so does a box made with let note: unknown. The
difference is what TypeScript lets you do with the value afterwards.
Lesson 6.9 showed what any lets you do: everything, with nothing
checked. Here someone gave task the type any, so that shout
would take any value at all. Run it:
tasks.tsts
function shout(task: any): string { return task.toUpperCase();}console.log(shout("pay rent"));console.log(shout(7));
TypeScript finds nothing, so it runs. It prints PAY RENT, then stops
on line 2 with the kind of TypeError lesson 6.9 met:
task.toUpperCase is not a function. Now change one word, any to
unknown, and run it again:
tasks.tsts
function shout(task: unknown): string { return task.toUpperCase();}console.log(shout("pay rent"));console.log(shout(7));
TypeScript refuses line 2 with TS18046 (TS for TypeScript, then the
number of the message), 'task' is of type 'unknown'., and Run on
this page starts nothing, not even the first call. (node tasks.ts
would still run it, as in lesson 8.2: Node does not check.) TypeScript
cannot know that task holds text, so it will not let you call a text
method on it. The mistake is the same in both files; what changes is
who finds it, and whether anything has run by then. Switch between the
two types, press Next step to walk through one, or let it play:
any spreads
An any does not stay in its own box. Whatever you get from it, a
property or what one of its methods gives back, is any too, and an
any fits a box of every type:
TypeScript finds nothing wrong, and it prints Pay, then Pay1.
Paste the code into a file in VS Code (Visual Studio Code, your
editor) and hover over first: it says any, because it came from
loose. So line 3 puts it in a box of type number, and TypeScript
says nothing. Now count holds text, and every line that uses count
believes it is a number, so count + 1 joins text instead of adding.
One any switches off the check for every value it touches, not only
for itself.
An unknown fits no box of another type, except any:
TypeScript refuses line 2 with Type 'unknown' is not assignable to type 'number'., and Run starts nothing.
Opening the safe box
Without a check, an unknown can do only what works on every value:
be printed, be put in a template string, be compared with ===, be
passed on to a function that takes unknown too. For anything more,
check what it holds first, with the checks you already have: typeof
(lesson 7.3) for text, numbers and true or false, and instanceof
(lesson 8.3) for an error. Inside the if, TypeScript knows the type,
as it did for a union. That is the fix for shout:
It prints PAY RENT, then Not text: 7. Inside the if, task
is a string, so toUpperCase is allowed. After it, task is
still unknown, so the last line only prints it.
A catch is where an unknown comes to you without asking. Here is
a function that turns whatever a catch got into one sentence. Pick
a value with the switch, press Next step to walk it through the
checks, or let it play:
caught: unknown
if caughtinstanceofError✓true
if typeofcaught==="string"–never asked
›prints Unknowncommand:removecaught:Error
›prints Noeggscaught:string
else›prints Somethingwentwrongcaught:unknown
next line
Each check opens the box a little: inside it, TypeScript
knows what caught holds
All 3 steps shown.Step 1 of 3: caught instanceof Error is trueStep 2 of 3: The block runs: Unknown command: removeStep 3 of 3: The next line
All 3 steps shown.
caught: unknown
if caughtinstanceofError✕false
if typeofcaught==="string"✓true
›prints Unknowncommand:removecaught:Error
›prints Noeggscaught:string
else›prints Somethingwentwrongcaught:unknown
next line
Each check opens the box a little: inside it, TypeScript
knows what caught holds
All 4 steps shown.Step 1 of 4: caught instanceof Error is falseStep 2 of 4: typeof caught === "string" is trueStep 3 of 4: The block runs: No eggsStep 4 of 4: The next line
All 4 steps shown.
caught: unknown
if caughtinstanceofError✕false
if typeofcaught==="string"✕false
›prints Unknowncommand:removecaught:Error
›prints Noeggscaught:string
else›prints Somethingwentwrongcaught:unknown
next line
Each check opens the box a little: inside it, TypeScript
knows what caught holds
All 4 steps shown.Step 1 of 4: caught instanceof Error is falseStep 2 of 4: typeof caught === "string" is falseStep 3 of 4: The block runs: Something went wrongStep 4 of 4: The next line
All 4 steps shown.
Each return ends the function, so a value that reaches the last line
is neither an Error nor text; that is why the figure calls that path
else. You know that, but TypeScript still calls it unknown, so the
last line does not guess: it gives back a sentence of its own.
Which one to write
When you know what a value holds, write its type: string, Task,
Command. That is the strictest promise, and TypeScript checks
every use of the value against it.
When you cannot know, write unknown, and check the value before you
use it. So far TypeScript gives you an unknown in one place only: a
catch. Everywhere else you write unknown yourself: for a parameter
meant to take every value, like the parameter of messageOf, and, in
Module 12, for the data your program gets from the web.
In your own code you will almost never need any. You will meet it in
code you did not write, like the values from Object.entries in
lesson 6.9. The place not to write it is the one where it is most
tempting: over a red line. Lesson 8.1 said never to widen a type to
hide a mistake. any is the widest of all, and it hides every later
mistake with that value, not only the one you saw.
TaskKit: a sentence for anything caught
TaskKit's catch from lesson 8.4 prints a message only when what it
caught is an Error. For anything else it prints nothing, and the
person sees the banner and silence. Every value TaskKit's own code
throws is an Error, so today that never happens. But the try will
hold more of your code as TaskKit grows. From Module 9 it will also
call code from packages: code other people wrote for you to use.
messageOf closes the gap.
1
Add messageOf
In index.ts in ~/projects/taskkit, add the function from this
lesson right above the line const version = "0.1";:
2
Use it in the catch
At the bottom of the file, the catch block holds three lines, from
if (error instanceof Error) { to its }. Replace them with one
line, so that the whole catch reads:
3
Check, run TaskKit, run the tests
Check the file with tsc (short for TypeScript compiler), which
npx starts, then run TaskKit and the tests:
The check prints nothing. TaskKit prints:
The same line as before, and node --test still counts pass 7.
4
See the last line of messageOf work
In the switch at the bottom of the file, put throw 7; on a line of
its own right under case "help":, and run node index.ts help:
With lesson 8.4's catch, the same throw would have printed nothing
at all. VS Code greys out the two lines under the throw: they can no
longer run. Then delete the throw 7; line again.
Predict what it prints
cook throws a string, as some code you did not write does, and
the catch takes the quick answer from the start of this lesson.
Read it and decide what it prints before you run it.
Predict
What does it print?
The common mistake: giving a catch a type
Once you know that catch (error: any) is allowed, it is tempting
to write the type you expect instead.
Common mistake
Giving the catch's box the type Error
parseDone from lesson 8.3 throws only errors, so you tell
TypeScript that only errors arrive:
TypeScript refuses line 10 with TS1196. Any value can be thrown, by
any line in the try or in a function it calls. So it will not take
your word that only errors arrive: the type could be a lie.
Catch clause variable type annotation must be 'any' or 'unknown' if specified.
The fix
Leave the type out, so the box is unknown, and check it:
It prints Not a number: ten. When TypeScript says the type of a
catch's box must be 'any' or 'unknown', take the type off the box.
If you expect an Error, say so inside, with if (error instanceof Error).
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. 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
What is the difference between any and unknown?
Check yourself
Which types may a catch's box be given?
Check yourself
Which type fits a parameter meant to take any value?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
any vs unknown
What things are
Word
What it means
any
Any value; every use of it passes unchecked
unknown
Any value, used only after a check
Escape hatch
any: out of the error, and out of every check
Safe box
unknown: anything goes in, nothing out unchecked
Code
Write
To
value: unknown
Take any value, and check it before use
typeof value === "string"
Use it as text inside the if
value instanceof Error
Use it as an error inside the if
messageOf(error)
One sentence for anything a catch gets
Rules
Rule
What it means
You know the type
Write it
You cannot know it
Write unknown, and check
A red line
Fix the code; never hide it with any
any spreads
What you get from it is any too
Unchecked unknown
Print, compare, pass on, put in a template string
unknown in a box
Fits no other type but any until a check
A catch's box
No type, unknown or any; nothing else
Where to go next
You can now tell any from unknown, open an unknown with
typeof and instanceof, and choose the type that keeps TypeScript
checking. TaskKit's catch has a sentence for anything it catches.
Next is Debugging strategies: console, breakpoints, isolating
the problem. TypeScript now finds more of your mistakes before the
run; that lesson is about the ones only a run shows, and how to find
the line where a program first goes wrong.
Before you move on, hover over three values in TaskKit's index.ts
and say each type before you look: word in readCommand, error
in the catch, and caught inside each if of messageOf.
You
TypeScript
Node
You: save tasks.tssavetasks.tssavetasks.ts
TypeScript: checked ✓checked✓checked✓
You: node tasks.tsnodetasks.tsnodetasks.ts
Node: PAY RENTPAYRENTPAYRENT
Node: TypeErrorTypeErrorTypeError
Time
shout takes task: any, and line 5 calls it with 7.
Nothing to check: every use of an any passes.
TypeScript found nothing, so you run it.
The first call gets text, and prints it in capitals.
Line 2, with 7: task.toUpperCase is not a function.
The same mistake: with any, Node finds it while it runs;
with unknown, TypeScript finds it first
All 5 steps shown.Step 1 of 5: You: save tasks.tsStep 2 of 5: TypeScript: checked ✓Step 3 of 5: You: node tasks.tsStep 4 of 5: Node: PAY RENTStep 5 of 5: Node: TypeError
All 5 steps shown.
You
TypeScript
Node
You: save tasks.tssavetasks.tssavetasks.ts
TypeScript: TS18046TS18046TS18046
You: fix line 2fixline2fixline2
Node: not run yetnotrunyetnotrunyet
Time
shout takes task: unknown, and line 5 calls it with 7.
Line 2: 'task' is of type 'unknown'. Nothing has run.
You add a typeof check before toUpperCase, instead of
running it.
You fixed it before running it, so Node never meets the mistake.
The same mistake: with any, Node finds it while it runs;
with unknown, TypeScript finds it first
All 4 steps shown.Step 1 of 4: You: save tasks.tsStep 2 of 4: TypeScript: TS18046Step 3 of 4: You: fix line 2Step 4 of 4: Node: not run yet
All 4 steps shown.
Exercise · Read the code
What an unchecked unknown may do
note is unknown. Which line does TypeScript refuse?
function cook(eggs: number): string { if (eggs === 0) { throw "No eggs"; } return "Omelette";}try { console.log(cook(0));} catch (error: any) { console.log(error.message);}
done.tsts
function parseDone(typed: string): number { const done = Number(typed); if (Number.isNaN(done)) { throw new Error(`Not a number: ${typed}`); } return done;}try { console.log(parseDone("ten"));} catch (error: Error) { console.log(error.message);}
done.tsts
function parseDone(typed: string): number { const done = Number(typed); if (Number.isNaN(done)) { throw new Error(`Not a number: ${typed}`); } return done;}try { console.log(parseDone("ten"));} catch (error) { if (error instanceof Error) { console.log(error.message); }}
Exercise · Fix the error
Close the escape hatch
titleLength counts the characters of a title without the spaces
around it, and it was given any so that it would take any value.
With 7 it stops with a TypeError. Change any to unknown, and
give back 0 for anything that is not text. It should print 8,
then 0.
Loading the editor…
Exercise · Write the code
Minutes from anything
minutesOf gets a value someone typed or a program passed on, and
must give back minutes. A number comes back as it is. Text that
Number turns into a number, such as "40", comes back as that
number. Anything else, like "soon" or true, throws an Error
with the message Not minutes.