16.1 Throwing an Error
Before you start, set up a new project folder named day16 exactly as you set up your project on Day 13: npm init -y, "type": "module" in package.json, npm install --save-dev typescript @types/node, and the same tsconfig.json. Every program today goes in that folder.
Until today, every program has worked on values you typed into the code yourself, so you knew they were sensible. Real programs read values from people and from files, and those values are often wrong. Someone types seventeen where you asked for an age. A saved file was written by an older version of your program and has a field missing. Today is about what a program should do when a value is bad, and how TypeScript helps you notice.
Start with what happens if you do nothing. This function reads an age from text with Day 2’s Number():
function parseAge(text: string): number {
return Number(text);
}
const age = parseAge("seventeen");
console.log(`Next year you will be ${age + 1}.`);
console.log(age >= 18 ? "Adult ticket" : "Child ticket");Next year you will be NaN.
Child ticket
Number("seventeen") cannot read the word, so, as Day 2 showed, it gives NaN. The function returns NaN as if it were an age, and nothing complains. NaN + 1 is NaN, so line 6 shows nonsense. Worse, line 7 sells a child ticket: NaN >= 18 is false, because every comparison with NaN is false. The bad value has quietly turned into a wrong decision. A function that cannot do its job should stop and say so loudly, not hand back a value that looks fine.
JavaScript has a statement for exactly this. throw stops the function at once and reports a problem to whoever called it. What you throw is normally an error object, made with new Error("message"). Error is a class built into JavaScript (a class like the ones you wrote on Day 15), and every error object has a message property: the text you passed in, describing what went wrong.
Worked example: parseAge refuses to guess
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
console.log(parseAge("17"));
console.log(parseAge("seventeen"));
console.log("Done");npx tsc reports no errors. node throw-age.ts shows this (your terminal shows the full path to your own folder where ... appears here):
17
file:///.../day16/throw-age.ts:4
throw new Error(`"${text}" is not a number`);
^
Error: "seventeen" is not a number
at ...| Line | What happens |
|---|---|
| 9 | parseAge("17"): Number("17") is 17, not NaN, so line 6 returns it, and 17 is shown |
| 10 | parseAge("seventeen"): age is NaN, so the if on line 3 is true |
| 4 | throw stops parseAge; line 6 never runs, and nothing is returned |
| 10 | The call never finishes, so console.log on line 10 never gets a value to show |
| 11 | Never runs: an error nobody handles stops the whole program, like Day 1’s RangeError |
Read the report exactly as Day 1 taught you to read a runtime error: the file and line where the program stopped (throw-age.ts:4), the code line with a caret, then the line naming the error. This time you wrote that last line: Error is the kind of error, and after the colon comes your own message. A good message says what was wrong with which value, so whoever reads it can fix the input.
Notice what the type checker said: nothing. parseAge promises to return a number, and every path through it either returns a number or throws, so the promise holds. A throw is not a return: the function gives back no value at all, so the checker has nothing to compare with number.
An error object is an ordinary value until you throw it. Making one does nothing by itself:
const problem = new Error("The tank is empty");
console.log(problem.message);
console.log(problem.name);
console.log(typeof problem);
console.log("Nothing was thrown, so the program goes on.");The tank is empty
Error
object
Nothing was thrown, so the program goes on.
Line 2 shows the message. Every error object also has a name property, the kind of error, which for a plain Error is "Error"; it is the word Node showed before the colon. typeof says "object", as it does for every object. Only throw turns the object into a stopped program.
Key idea
throw new Error("what went wrong") stops the current function at once and reports the problem to its caller. If
nothing handles it, the program stops with the message. Throw when a function cannot do its job, rather than returning
a value that only looks right.
Watch out
Returning the error instead of throwing it. return and throw look alike, and it is easy to type the wrong one:
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
return new Error(`"${text}" is not a number`);
}
return age;
}
console.log(parseAge("17"));return-error.ts:4:5 - error TS2322: Type 'Error' is not assignable to type 'number'.The checker catches this one: the function promised a number, and line 4 returns an Error object. A returned error is just a value; it does not stop anything, and the caller would go on as if it were an age. Change return to throw. Fix or delete this file before your next check.
Pause and try
Question 1 · Tracing
npx tsc reports no errors. Write everything node predict-throw.ts shows, up to and including the line naming the error.
function checkStock(item: string, count: number): number {
console.log(`Checking ${item}`);
if (count <= 0) {
throw new Error(`${item} is out of stock`);
}
console.log(`${item} is in stock`);
return count;
}
checkStock("pens", 12);
checkStock("rulers", 0);
checkStock("erasers", 5);Check your reasoning
Checking pens
pens is in stock
Checking rulers
file:///.../predict-throw.ts:4
throw new Error(`${item} is out of stock`);
^
Error: rulers is out of stock- Line 10:
countis 12, so nothrow; both messages show and 12 is returned (and ignored). - Line 11: line 2 shows
Checking rulers, then0 <= 0istrue, so line 4 throws. Line 6 is skipped. - Nothing handles the error, so the program stops: line 12 never runs, and
erasersis never checked.
Reread 16.1 Throwing an Error if any line differed.
Question 2 · Multiple choice
A function is declared function price(size: string): number. Which line inside it does npx tsc reject?
throw new Error("No such size");return new Error("No such size");const problem = new Error("No such size");throw new Error("No such size: " + size);
Check your reasoning
B. The function promised to return a number, and an Error is not a number: TS2322.
- A is wrong: a
throwreturns nothing, so the return type is not involved. It is accepted. - C is wrong: making an error object and storing it is allowed; it simply does nothing until it is thrown.
- D is wrong:
"No such size: " + sizeis a string like any other, so this is the same as A with a more helpful message.
Reread 16.1 Throwing an Error if you chose differently.
16.2 Catching with try and catch
Throwing is half the story. A program that stops at the first bad answer is not much better than one that shows NaN. A sign-up program reading three ages should report the bad one and carry on with the rest. It needs a way to say: “try this; if it throws, do this instead.”
That is a try / catch statement. You put the code that might throw in a try block, and the code to run if it does in a catch block:
try {
// code that might throw
} catch {
// runs only if something in the try block threw
}
If nothing in the try block throws, the catch block is skipped. If something throws, the rest of the try block is skipped, the catch block runs, and then the program carries on after the whole statement as normal. A thrown error that a catch block receives is said to be caught; one that nobody catches stops the program, as in 16.1, and is called uncaught.
Worked example: Three ages, one bad
parseAge is the same as in 16.1. This time the calls are inside a try block:
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
const answers = ["17", "seventeen", "42"];
for (const answer of answers) {
try {
const age = parseAge(answer);
console.log(`Age ${age} saved`);
} catch {
console.log(`Could not read "${answer}", skipped`);
}
}
console.log("Done");Age 17 saved
Could not read "seventeen", skipped
Age 42 saved
Doneanswer |
Line 13 | Line 14 | Line 16 |
|---|---|---|---|
"17" |
returns 17 | runs | skipped |
"seventeen" |
throws at line 4 | skipped | runs |
"42" |
returns 42 | runs | skipped |
For "seventeen", the throw on line 4 ends parseAge, and then it ends the rest of the try block too: line 14 is skipped, so there is no “saved” message for a bad age. Control jumps to the catch block on line 15. After line 16, the try statement is finished and the loop goes on to "42" as if nothing had happened. The program never stops, and line 19 runs.
The throw happened inside parseAge, but the catch is in the code that called it. That is the point: the function that finds a problem often does not know what to do about it, while the caller does (skip it, ask again, use a default). An error travels up through the calls until it reaches a try block, leaving every function on the way without finishing it. Vary the example to see an error pass through two functions:
function parsePrice(text: string): number {
const price = Number(text);
if (Number.isNaN(price)) {
throw new Error(`Bad price: ${text}`);
}
return price;
}
function orderTotal(prices: string[]): number {
let total = 0;
for (const text of prices) {
total += parsePrice(text);
console.log(`Running total: ${total}`);
}
return total;
}
try {
console.log(orderTotal(["2.50", "four", "1.25"]));
console.log("Total printed");
} catch {
console.log("The order could not be totaled");
}
console.log("Next order");Running total: 2.5
The order could not be totaled
Next order
The try block on line 18 calls orderTotal, which calls parsePrice in a loop. "2.50" is fine, so line 13 shows a running total. "four" throws on line 4. parsePrice stops; orderTotal stops too, in the middle of its loop, without reaching "1.25" or its return; line 19 never gets a total to show, and line 20 is skipped. The catch block on line 21 is the first one the error reaches. After it, line 24 runs as usual.
Look at line 15 of catch-age.ts and line 21 here: catch is followed straight by {. You can also write catch (error) to receive the thing that was thrown, which 16.4 does. When you do not need it, leave the parentheses out.
Key idea
Code in a try block runs until something throws. Then the rest of the try block is skipped, the catch block
runs, and the program carries on after the statement. An error travels up through every function call, stopping each
one, until a catch receives it.
Watch out
A variable trapped inside the try block. A try block is a block, so Day 8’s scope rules apply: a const declared inside it does not exist after the closing }.
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
try {
const age = parseAge("17");
} catch {
console.log("Could not read the age");
}
console.log(`Age: ${age}`);try-scope.ts:14:21 - error TS2304: Cannot find name 'age'.It is Day 1’s “cannot find name” message, because line 14 is outside the block that declared age. Do the work that needs the value inside the try block, right after the line that might throw:
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
try {
const age = parseAge("17");
console.log(`Age: ${age}`);
} catch {
console.log("Could not read the age");
}Age: 17This also reads well: the “happy path” sits together in the try block, and the catch block holds only what to do if it fails. When the value really is needed after the statement, declare it before the try block with let and assign it inside; 16.10 does that. Fix or delete try-scope.ts before your next check.
Pause and try
Question 3 · Tracing
Predict exactly what this program shows.
function half(n: number): number {
if (n % 2 !== 0) {
throw new Error(`${n} is odd`);
}
return n / 2;
}
for (const n of [8, 5, 6]) {
try {
console.log("A");
console.log(half(n));
console.log("B");
} catch {
console.log("C");
}
}
console.log("D");Check your reasoning
A
4
B
A
C
A
3
B
Dnis 8:A, thenhalf(8)returns 4, thenB. Thecatchblock is skipped.nis 5:A, then5 % 2is 1, sohalfthrows. Theconsole.logon line 11 never gets a value, so nothing shows for it, and line 12 is skipped. Thecatchblock showsC.nis 6:A,3,B.- After the loop,
D.
Reread 16.2 Catching with try and catch if any line differed.
Question 4 · Multiple choice
In unwind.ts, suppose the prices were ["2.50", "1.25", "four"] instead. What would the program show?
Running total: 2.5,Running total: 3.75,The order could not be totaled,Next orderRunning total: 2.5,Running total: 3.75,3.75,Total printed,Next orderRunning total: 2.5,Running total: 3.75,The order could not be totaledThe order could not be totaled,Next order
Check your reasoning
A. The first two prices are read and each shows a running total. "four" throws inside the loop, which stops orderTotal before its return, so there is no total to show and Total printed is skipped. The catch block runs, and then the program carries on to Next order.
- B is wrong: a function that is stopped by a throw returns nothing, not the total so far.
- C is wrong: once the
catchblock has run, the error is handled and the program continues with line 24. - D is wrong: the lines before the bad price have already run, and their output stays on the screen.
Reread 16.2 Catching with try and catch if you chose differently.
16.3 Cleaning Up with finally
Sometimes a job has a last step that must happen whether or not the middle part worked. A shop unlocks the till drawer, tries to record a sale, and must lock the drawer again even when the sale fails. A program opens a file, reads it, and must close it. You could write the last step twice, once at the end of the try block and once in the catch block, but then a third path (say, a return in the middle) could miss it.
A finally block goes after catch (or straight after try) and runs every time, after the try block finishes normally, after the catch block, and even when the try block returns:
Worked example: Lock the door every time
function parseScore(text: string): number {
const score = Number(text);
if (Number.isNaN(score)) {
throw new Error(`"${text}" is not a score`);
}
return score;
}
function addScore(text: string): void {
console.log("Door unlocked");
try {
const score = parseScore(text);
console.log(`Saved ${score}`);
} catch {
console.log(`Rejected "${text}"`);
} finally {
console.log("Door locked");
}
}
addScore("88");
addScore("eighty");Door unlocked
Saved 88
Door locked
Door unlocked
Rejected "eighty"
Door lockedFor "88", the try block runs to the end, the catch block is skipped, and the finally block runs. For "eighty", line 12 throws, line 13 is skipped, the catch block runs, and then the finally block runs. Either way, “Door locked” is the last thing addScore does.
Now vary it so the try block returns a value:
function parseScore(text: string): number {
const score = Number(text);
if (Number.isNaN(score)) {
throw new Error(`"${text}" is not a score`);
}
return score;
}
function scoreOrZero(text: string): number {
try {
return parseScore(text);
} catch {
return 0;
} finally {
console.log(`Checked "${text}"`);
}
}
console.log(scoreOrZero("91"));
console.log(scoreOrZero("ninety"));Checked "91"
91
Checked "ninety"
0
Look at the order. For "91", line 11 decides to return 91, but before the function actually hands the value back, the finally block runs and shows Checked "91". Only then does line 19 receive 91 and show it. A return cannot skip finally. For "ninety", line 11 throws, line 13 decides to return 0, and again the finally block runs first.
A try with a finally but no catch is allowed too. The finally block still runs, but nothing handles the error, so after the clean-up it carries on up to the caller exactly as if the try were not there. Question 5 shows what that looks like.
Key idea
A finally block runs after the try block and any catch block, every time: when nothing went wrong, when an error
was caught, when the try block returned, and even when the error is not caught. Put clean-up there.
Watch out
Thinking finally means “only after an error”. The name sounds like “finally, something went wrong,” but finally has nothing to do with errors; it means “at the very end, no matter what.” Code that should run only when something failed belongs in catch. In finally-door.ts, putting Rejected in the finally block would show it for the good score too.
Pause and try
Question 5 · Tracing
This try has no catch. npx tsc reports no errors. Write everything node finally-no-catch.ts shows, up to and including the line naming the error.
function parseScore(text: string): number {
const score = Number(text);
if (Number.isNaN(score)) {
throw new Error(`"${text}" is not a score`);
}
return score;
}
function addScore(text: string): void {
console.log("Door unlocked");
try {
console.log(`Saved ${parseScore(text)}`);
} finally {
console.log("Door locked");
}
}
addScore("75");
addScore("seventy");
addScore("60");Check your reasoning
Door unlocked
Saved 75
Door locked
Door unlocked
Door locked
file:///.../finally-no-catch.ts:4
throw new Error(`"${text}" is not a score`);
^
Error: "seventy" is not a scoreaddScore("75")works, andfinallylocks the door.addScore("seventy"): line 12 throws beforeSavedcan show. There is nocatch, but thefinallyblock runs anyway:Door locked. Then the error carries on up, out ofaddScoreand out of the program, which stops.addScore("60")never runs.
Reread 16.3 Cleaning Up with finally if any line differed.
16.4 The Caught Value Is unknown
A catch block that only says “could not read” is not very helpful. The thrown error has a message saying exactly what was wrong, and the catch block should show it. To get at the thrown thing, give the catch a name in parentheses, catch (error). The name is a new variable, like a parameter, that holds whatever was thrown. So this should work:
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
try {
console.log(parseAge("seventeen"));
} catch (error) {
console.log(error.message);
}catch-message-wrong.ts:12:15 - error TS18046: 'error' is of type 'unknown'.
The checker refuses. To see why, you need one surprising fact about JavaScript: you can throw anything, not only error objects. A string, a number, null:
function reserveSeat(seat: number): void {
if (seat > 30) {
throw "No such seat";
}
if (seat === 13) {
throw 13;
}
console.log(`Seat ${seat} reserved`);
}
for (const seat of [4, 31, 13]) {
try {
reserveSeat(seat);
} catch (error) {
console.log(typeof error, error);
}
}Seat 4 reserved
string No such seat
number 13
Line 3 throws a string and line 6 throws a number, and catch receives exactly what was thrown. Throwing things that are not errors is a bad habit, because they have no message and no name, but other people’s code and some older libraries do it. And a try block can call any function, which can call any other function, so the checker has no way to know what might arrive. The honest answer is: anything.
TypeScript has a type for that: unknown. A value of type unknown can be anything at all, and so the checker lets you do almost nothing with it: no properties, no methods, no arithmetic. TS18046, “is of type ‘unknown’,” is the message you get when you try. Strict mode makes every caught value unknown, and that is a good thing: error.message on a thrown string would be undefined, so the checker has just stopped you from showing undefined to a user.
To use an unknown value, narrow it, as you narrowed unions on Day 9. For errors, the check you want is instanceof. value instanceof Error is true when value is an object made with new Error(...), or with any class that extends Error. Here it is on its own:
const problem = new Error("Out of paper");
const words: unknown = "Out of paper";
const prices = new Map<string, number>();
console.log(problem instanceof Error);
console.log(words instanceof Error);
console.log(prices instanceof Map);
console.log(typeof problem, typeof prices);true
false
true
object object
Line 5 is true because problem was made with new Error. Line 6 is false: a string is not an error object, even when its text is the same. (words is declared unknown here because the checker rejects instanceof on something it already knows is a string: TS2358, “the left-hand side of an ‘instanceof’ expression must be … an object type.”) Line 7 shows that instanceof works with any class, here Day 7’s Map. Line 8 shows why Day 9’s typeof cannot do this job: it says "object" for both.
The checker follows instanceof like any other narrowing check:
Worked example: Showing the message safely
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
if (age > 130) {
throw "too old";
}
return age;
}
for (const answer of ["17", "seventeen", "200"]) {
try {
console.log(`Age ${parseAge(answer)}`);
} catch (error) {
if (error instanceof Error) {
console.log(`Error: ${error.message}`);
} else {
console.log(`Something odd was thrown: ${String(error)}`);
}
}
}Age 17
Error: "seventeen" is not a number
Something odd was thrown: too oldanswer |
What is thrown | Line 16 | Line that shows output |
|---|---|---|---|
"17" |
nothing | not run | 14 |
"seventeen" |
an Error (line 4) |
true |
17 |
"200" |
the string "too old" |
false |
19 |
Inside the if on line 16, error has been narrowed from unknown to Error, so error.message is allowed. In the else block it is still unknown, and line 19 uses String(error), which, like a template literal, accepts any value. Line 7 throws a string only to show the else branch working; your own code should always throw error objects.
Key idea
JavaScript can throw any value, so a caught value has the type unknown, and the checker rejects error.message with
TS18046. Narrow it with error instanceof Error before using message, and handle the other case with
String(error).
Watch out
Reaching for typeof error === "object". It narrows unknown to object | null, but an object type has no message property that the checker knows of, and a thrown {} or array would pass it too. instanceof Error is the check that proves the value really is an error object with a message.
Pause and try
Question 6 · Multiple choice
Inside catch (error) { ... }, which line does npx tsc accept?
console.log(error.message);console.log(error instanceof Error ? error.message : String(error));console.log(typeof error === "string" ? error : error.message);const message: string = error;
Check your reasoning
B. In the true branch of the conditional, error is narrowed to Error, so .message is allowed; the false branch uses String, which takes anything.
- A is wrong:
errorisunknown, so any property is TS18046. - C is wrong: the false branch knows only that
erroris not a string. It is still not known to be anError, so.messageis rejected. - D is wrong: an
unknownvalue cannot be assigned to astringwithout narrowing; the checker reports TS2322,Type 'unknown' is not assignable to type 'string'.
Reread 16.4 The Caught Value Is unknown if you chose differently.
Question 7 · Short answer
A classmate says, “The checker is being silly. My try block only calls parseAge, and parseAge only throws Error objects, so error must be an Error.” Explain why the checker still says unknown.
Check your reasoning
Model answer: JavaScript allows any value to be thrown, and a function’s type says nothing about what it might throw: parseAge(text: string): number describes only what it returns. So the checker cannot look at the try block and work out what will arrive. Even if parseAge throws only errors today, it may call another function that throws something else, or be changed later. Treating the value as unknown makes you check with instanceof Error once, which costs one line and is correct whatever arrives.
A complete answer must say that:
- any value can be thrown, not only
Errorobjects, and - a function’s type does not record what it throws, so the checker cannot know.
Reread 16.4 The Caught Value Is unknown if your reasoning differed.
16.5 Custom Error Classes
A program usually meets two very different kinds of failure. Some are expected: a person typed abc for their age, and the right response is a friendly “please try again.” Others are bugs: the program’s own code is wrong, and pretending all is well would hide it. Every Error looks the same to instanceof Error, and checking the message text (if (error.message.includes("not a number"))) breaks the day someone rewords a message. The caller needs a sturdier way to tell errors apart.
The answer uses Day 15. Error is a class, so you can write a custom error class that extends it. Every object made from it is still an Error, with a message and a name, and it can carry extra fields; but instanceof can also pick it out by its own class name.
Worked example: An AgeError class
class AgeError extends Error {
readonly text: string;
constructor(text: string, reason: string) {
super(`Age ${reason}`);
this.name = "AgeError";
this.text = text;
}
}
function parseAge(text: string): number {
const age = Number(text);
if (text.trim() === "" || Number.isNaN(age)) {
throw new AgeError(text, "must be a number");
}
if (age < 0 || age > 130) {
throw new AgeError(text, "must be between 0 and 130");
}
return age;
}
for (const answer of ["17", "abc", "200"]) {
try {
console.log(`Age ${parseAge(answer)}`);
} catch (error) {
if (error instanceof AgeError) {
console.log(`${error.name}: ${error.message} (you typed "${error.text}")`);
} else {
throw error;
}
}
}Age 17
AgeError: Age must be a number (you typed "abc")
AgeError: Age must be between 0 and 130 (you typed "200")| Line | What it does |
|---|---|
| 1 | AgeError extends Error, so it has everything an Error has |
| 2 | An extra field, text: the input that was rejected. readonly, because it should never change |
| 5 | super(...) runs Error’s own constructor, which stores the message |
| 6 | Sets name, so the error reports itself as an AgeError |
| 13 | text.trim() === "" also catches empty input, because Number("") is 0, not NaN |
| 14, 17 | Two different reasons, both thrown as AgeError |
| 26 | instanceof AgeError narrows error to AgeError, so name, message, and text are all allowed |
| 29 | Anything else is not ours to handle, so it is thrown again |
Line 29 is new: a throw inside a catch block. It is called rethrowing. The catch block received something it does not understand, a bug perhaps, and instead of hiding it, it sends it on up, to an outer catch if there is one or to the top, where it stops the program with its full report. A catch block should handle only the errors it knows what to do with.
Why set name on line 6? Without it, a subclass inherits Error’s name, "Error", so the report would not say which kind of error it is. Compare the two:
class PlainError extends Error {}
class NamedError extends Error {
constructor(message: string) {
super(message);
this.name = "NamedError";
}
}
const plain = new PlainError("first");
const named = new NamedError("second");
console.log(String(plain));
console.log(String(named));
console.log(plain instanceof PlainError, plain instanceof Error);
console.log(named instanceof PlainError);Error: first
NamedError: second
true true
false
String(error) gives name: message, which is also how Node starts the report of an uncaught error. PlainError forgot to set name, so it calls itself just Error. Line 15 shows that an object made from a subclass is an instance of both its own class and Error; line 16 shows that two subclasses of Error are not instances of each other.
Key idea
A custom error class (class AgeError extends Error) calls super(message), sets this.name, and may add fields.
Callers pick it out with instanceof AgeError, handle it, and rethrow anything else with throw error;.
Watch out
Checking instanceof Error first. Because an AgeError is also an Error, the order of checks matters:
class AgeError extends Error {
constructor(message: string) {
super(message);
this.name = "AgeError";
}
}
function describe(error: unknown): string {
if (error instanceof Error) {
return "A bug in the program";
}
if (error instanceof AgeError) {
return "Please type your age again";
}
return "Something odd was thrown";
}
console.log(describe(new AgeError("abc is not a number")));
console.log(describe(new Error("total was undefined")));A bug in the program
A bug in the programLine 9 is true for every error object, AgeError included, so the function returns there and line 12 can never be reached for an error object. The checker does not complain: nothing here is a type mistake, just an order mistake. Check the most specific class first, like an if chain on Day 4 that tests the highest grade band first:
class AgeError extends Error {
constructor(message: string) {
super(message);
this.name = "AgeError";
}
}
function describe(error: unknown): string {
if (error instanceof AgeError) {
return "Please type your age again";
}
if (error instanceof Error) {
return "A bug in the program";
}
return "Something odd was thrown";
}
console.log(describe(new AgeError("abc is not a number")));
console.log(describe(new Error("total was undefined")));Please type your age again
A bug in the programPause and try
Question 8 · Tracing
npx tsc reports no errors. Write everything node rethrow.ts shows, up to and including the line naming the error.
class AgeError extends Error {
constructor(message: string) {
super(message);
this.name = "AgeError";
}
}
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new AgeError(`"${text}" is not a number`);
}
return age;
}
function birthYear(text: string, thisYear: number): number {
if (thisYear < 2000) {
throw new Error(`thisYear looks wrong: ${thisYear}`);
}
return thisYear - parseAge(text);
}
const tests: [string, number][] = [
["17", 2026],
["abc", 2026],
["30", 26],
];
for (const [answer, year] of tests) {
try {
console.log(birthYear(answer, year));
} catch (error) {
if (error instanceof AgeError) {
console.log(`Try again: ${error.message}`);
} else {
throw error;
}
}
}Check your reasoning
2009
Try again: "abc" is not a number
file:///.../rethrow.ts:18
throw new Error(`thisYear looks wrong: ${thisYear}`);
^
Error: thisYear looks wrong: 26["17", 2026]: 2026 is not below 2000, and2026 - 17is 2009.["abc", 2026]:parseAgethrows anAgeError; line 33 istrue, so the message is shown and the loop goes on.["30", 26]: 26 is below 2000, so line 18 throws a plainError. It is not anAgeError, so line 36 rethrows it. Nothing outside catches it, so the program stops. The report points at line 18, where the error was made, not line 36, where it was rethrown: an error remembers where it came from, which is what makes rethrowing useful.
Reread 16.5 Custom Error Classes if any line differed.
Question 9 · Multiple choice
class StockError extends Error has a constructor that calls super(message) but does not set this.name. What does String(new StockError("pens sold out")) give?
StockError: pens sold outError: pens sold outpens sold out[object Object]
Check your reasoning
B. String of an error gives name: message, and a subclass that does not set name inherits "Error" from Error.
- A is wrong: that is what you get after
this.name = "StockError";, which is why custom error classes set it. - C is wrong: that is only the
message;Stringputs the name in front. - D is wrong: error objects have their own way of turning into text, so
Stringgives the name and message, not the general object text.
Reread 16.5 Custom Error Classes if you chose differently.
16.6 any Versus unknown
unknown is the checker’s careful type for “could be anything.” TypeScript has a second type for the same situation, with the opposite attitude, and you will meet it in other people’s code and in a few built-in functions. any means “could be anything, and I will not check it.” Where unknown allows almost nothing until you narrow, any allows everything: every property, every method, every assignment. In effect, any switches the type checker off for that value.
Worked example: any lets a crash through
let reading: any = 42;
console.log(reading.toUpperCase());npx tsc reports no errors. node any-crash.ts stops with:
TypeError: reading.toUpperCase is not a functionreading holds 42, a number, which has no toUpperCase. Day 3 and Day 9 relied on the checker to stop exactly this mistake before the program ran. With any, it agreed to anything, so the mistake surfaced only as a runtime error.
Change one word, any to unknown, and the checker is back on duty:
const reading: unknown = 42;
console.log(reading.toUpperCase());unknown-safe.ts:2:13 - error TS18046: 'reading' is of type 'unknown'.
To use an unknown value you must first prove what it is, with the same checks as Day 9:
function shout(reading: unknown): string {
if (typeof reading === "string") {
return reading.toUpperCase();
}
return `(not text: ${String(reading)})`;
}
console.log(shout("hello"));
console.log(shout(42));
console.log(shout(null));HELLO
(not text: 42)
(not text: null)
Inside the if, typeof has narrowed reading to string, so toUpperCase is allowed. Every other value takes the safe path.
any has a second danger: it spreads. An any value can be assigned to a variable of any type without complaint, and from then on that variable’s type is a lie:
const reading: any = 42;
const label: string = reading;
console.log(label.length);undefined
Line 2 puts 42 into a variable annotated string. The checker accepts it, because reading is any. Now every later line trusts label to be a string, but it holds a number, and a number’s length is undefined. The program did not even crash; it just printed a wrong answer, which is harder to notice.
| Question | any |
unknown |
|---|---|---|
| Can it hold any value? | Yes | Yes |
| Can you use a property or method directly? | Yes, unchecked | No: TS18046 until you narrow |
Can you assign it to a string variable? |
Yes, unchecked | No: TS2322 until you narrow |
| Who finds a wrong guess? | Node, at run time, if at all | The checker, before the program runs |
Key idea
any and unknown can both hold any value. any turns checking off and lets mistakes through to run time; unknown
keeps checking on and makes you narrow first. When a value really could be anything, use unknown.
Watch out
Writing any to make an error message go away. When the checker complains, : any makes the complaint vanish, and it is tempting. But the message was telling you about a real possibility, and any does not change what the value is at run time; it only stops the checker from looking. Read the message and narrow instead.
Pause and try
Question 10 · Multiple choice
let a: any = "hi"; and let u: unknown = "hi";. Which line does npx tsc reject?
console.log(a.length);const n: number = a;console.log(u.length);console.log(typeof u === "string" ? u.length : 0);
Check your reasoning
C. u is unknown, so reading a property without narrowing is TS18046.
- A is wrong:
anyallows any property. (It shows 2.) - B is wrong, and worth a second look: the checker accepts putting an
anyinto anumbervariable even though it holds a string. That is the “spreading” danger, and it is accepted, not rejected. - D is wrong:
typeof u === "string"narrowsutostringin the true branch, so.lengthis allowed.
Reread 16.6 any Versus unknown if you chose differently.
16.7 JSON.parse Returns any
Data that comes from outside your program, from a file, from the internet (Day 17), or from what a person typed, is where any and unknown matter most. The most common format for that data is JSON (JavaScript Object Notation): text that looks like a JavaScript object or array literal, with every property name and every string in double quotes. A JSON file of books might hold:
[
{ "title": "Dune", "pages": 412 },
{ "title": "Emma", "pages": 474 }
]
It is only text: a long string of characters, until a program reads it. JSON.parse(text) reads JSON text and builds the real values it describes: objects, arrays, strings, numbers, booleans, and null. JSON.stringify(value) does the opposite and turns a value into JSON text. On Day 13 you read a text file with readFileSync; JSON.parse is the next step, turning that text into data. To keep today’s programs in one file, the JSON is written into a string constant instead.
const text = '{"title": "Dune", "pages": 412, "tags": ["classic", "space"]}';
const book = JSON.parse(text);
console.log(typeof text);
console.log(book.title);
console.log(book.pages + 1);
console.log(book.tags.length);
console.log(JSON.stringify(book));string
Dune
413
2
{"title":"Dune","pages":412,"tags":["classic","space"]}
text is a string (line 4). After line 2, book is an object with a title, a number pages (so book.pages + 1 is 413, not "4121"), and an array tags. Line 8 turns it back into JSON text.
Now hover over book in VS Code: its type is any. The checker cannot know what is inside a string until the program runs, so JSON.parse is declared to return any. And 16.6 showed what any means: no checking. Here is the danger in practice. The program expects books with a title, but this file was written by another program that called it name:
type Book = { title: string; pages: number };
const text = '{"name": "Dune", "pages": 412}';
const book: Book = JSON.parse(text);
console.log(`Pages: ${book.pages}`);
console.log(book.title.toUpperCase());npx tsc reports no errors. node json-any-bug.ts shows:
Pages: 412
TypeError: Cannot read properties of undefined (reading 'toUpperCase')
Line 4’s annotation : Book looks like a check, but it is not one: an any can be assigned to anything (16.6), so the checker simply believes it. At run time, book.title is undefined, and the crash happens three lines later, far from the real problem, which was trusting the data.
The fix is to say honestly what you know: the parsed value could be anything. Annotate it unknown:
type Book = { title: string; pages: number };
const text = '{"name": "Dune", "pages": 412}';
const data: unknown = JSON.parse(text);
const book: Book = data;
console.log(book.title.toUpperCase());json-unknown.ts:5:7 - error TS2322: Type 'unknown' is not assignable to type 'Book'.
Now the checker refuses to treat the data as a Book until you have checked that it is one, which is 16.8. Fix or delete this file before your next check.
JSON.parse can also fail outright. If the text is not valid JSON, such as {pages: 412} (the name has no double quotes) or 'hello' (single quotes), it throws a SyntaxError, another built-in subclass of Error. So reading outside data has two separate risks: the text may not be JSON at all, and the JSON may not have the shape you expect. instanceof handles the first:
function parseJson(text: string): unknown {
try {
return JSON.parse(text);
} catch (error) {
if (error instanceof SyntaxError) {
console.log(`Not valid JSON: ${text}`);
return undefined;
}
throw error;
}
}
console.log(parseJson('{"pages": 412}'));
console.log(parseJson("{pages: 412}"));
console.log(parseJson("[1, 2, 3]"));
console.log(parseJson("'hello'"));{ pages: 412 }
Not valid JSON: {pages: 412}
undefined
[ 1, 2, 3 ]
Not valid JSON: 'hello'
undefined
parseJson returns unknown, which is the honest type. When JSON.parse throws a SyntaxError, line 6 reports it and the function returns undefined; anything else is rethrown as in 16.5. Node shows a parsed object without the quotes around its property names, as it showed objects on Day 7.
Key idea
JSON.parse turns JSON text into values, throws a SyntaxError for text that is not JSON, and returns any. Store
its result as unknown (const data: unknown = JSON.parse(text);) so the checker makes you check the shape before
you use it.
Pause and try
Question 11 · Tracing
Predict exactly what this program shows.
const text = '{"name": "Ana", "scores": [12, 19], "captain": true}';
const player = JSON.parse(text);
console.log(player.name.length);
console.log(player.scores[1] - player.scores[0]);
console.log(player.captain ? "Captain" : "Player");
console.log(player.team);
console.log(JSON.stringify(player.scores));Check your reasoning
3
7
Captain
undefined
[12,19]- Line 4:
player.nameis the string"Ana", which has 3 characters. - Line 5:
scoresis a real array of numbers, so19 - 12is 7. - Line 6:
captainis the booleantrue, so the conditional gives Captain. - Line 7: there is no
teamin the JSON, so reading it givesundefined. Becauseplayerisany, the checker did not warn you; with a typed object it would have. - Line 8:
JSON.stringifywrites the array back as JSON text, with no spaces.
Reread 16.7 JSON.parse Returns any if any line differed.
Question 12 · Multiple choice
Which line is the safest way to read a JSON string text that should hold a Book?
const book = JSON.parse(text);const book: Book = JSON.parse(text);const data: unknown = JSON.parse(text);const data: any = JSON.parse(text);
Check your reasoning
C. unknown tells the truth: until it is checked, the data could be anything, so the checker will reject every use of it until you prove it is a Book.
- A is wrong: with no annotation,
bookisany, so every mistake is left for run time. - B is wrong: it only looks safe. The checker accepts assigning
anytoBookwithout checking anything, asjson-any-bug.tsshowed. - D is wrong: it is A with the
anywritten out.
Reread 16.7 JSON.parse Returns any if you chose differently.
16.8 Type Guards
You have an unknown value and you want a Book. Day 9’s narrowing checks can prove it, one step at a time, and the checker follows each step:
| Check | What the checker knows afterwards |
|---|---|
typeof value === "object" |
object or null (Day 2: typeof null is "object") |
value !== null |
object |
"title" in value |
an object that has a title, of type unknown |
typeof value.title === "string" |
that title is a string |
in on an unknown object works as on Day 9: after "title" in value, the checker lets you read value.title, but it knows nothing about what is in it, so its type is unknown too, and you check that next. Writing all of that every time you need a book would be long and repetitive. Instead, you put it in a function, once.
A function that checks a value’s type and tells the checker the answer is called a type guard. It looks like any function that returns a boolean, except for its return type:
function isBook(value: unknown): value is Book;
value is Book is a type predicate. It means: “this function returns a boolean, and when it returns true, value is a Book.” Where the function is called in a condition, the checker narrows the argument just as it would after typeof.
Worked example: isBook
type Book = { title: string; pages: number };
function isBook(value: unknown): value is Book {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);
}
const texts = [
'{"title": "Dune", "pages": 412}',
'{"name": "Dune", "pages": 412}',
'{"title": "Emma", "pages": "474"}',
'"Dune"',
"null",
];
for (const text of texts) {
const data: unknown = JSON.parse(text);
if (isBook(data)) {
console.log(`${data.title.toUpperCase()}: ${data.pages} pages`);
} else {
console.log(`Not a book: ${text}`);
}
}DUNE: 412 pages
Not a book: {"name": "Dune", "pages": 412}
Not a book: {"title": "Emma", "pages": "474"}
Not a book: "Dune"
Not a book: nullLines 5 to 10 are the four steps from the table, twice: once for title and once for pages. They are joined with &&, so, as Day 4 taught, the first false stops the chain and every later check can rely on the earlier ones (line 8 may read value.title only because line 7 proved it exists).
| JSON | Where it fails | Result |
|---|---|---|
{"title": "Dune", "pages": 412} |
Nowhere | Book |
{"name": "Dune", "pages": 412} |
Line 7: no title |
Not a book |
{"title": "Emma", "pages": "474"} |
Line 10: pages is a string |
Not a book |
"Dune" |
Line 5: a string is not an object | Not a book |
null |
Line 6 | Not a book |
On line 24, isBook(data) is true only for the first, and inside that if, data is a Book, so data.title.toUpperCase() is allowed. The bad JSON from 16.7 no longer crashes anything; it is reported and skipped.
The guard checks every property the type says is required, and their types too. The third input is why: "474" in quotes is a string in JSON, and a guard that checked only that pages exists would let it through. An extra property that the type does not mention is fine; the guard ignores it, as the type does.
Watch out
A guard that checks too little. The checker trusts your predicate completely. It does not read the function body to see whether the checks match value is Book; whatever the function returns, it believes:
type Book = { title: string; pages: number };
function isBook(value: unknown): value is Book {
return typeof value === "object" && value !== null && "title" in value && "pages" in value;
}
const data: unknown = JSON.parse('{"title": "Emma", "pages": "474"}');
if (isBook(data)) {
console.log(`With the preface: ${data.pages + 12} pages`);
}With the preface: 47412 pagesThis guard checks that pages exists, not that it is a number. The JSON has "pages": "474", a string, so isBook says true, the checker treats data.pages as a number, and Day 3’s rule turns "474" + 12 into "47412". No error anywhere, just a wrong answer. Check the type of each property, as book-guard.ts does, not only that it is there.
You may wonder why the checker does not narrow an object property that you skipped. If you check that a value is an object and then reach for title without in, it refuses:
function titleOf(value: unknown): string {
if (typeof value === "object" && value !== null) {
return value.title;
}
return "untitled";
}
console.log(titleOf({ title: "Emma" }));narrow-skip.ts:3:18 - error TS2339: Property 'title' does not exist on type 'object'.
The type object means “some object,” with no properties the checker knows of, so you must prove each one with in. Fix or delete this file.
Key idea
A type guard is a function returning value is Book: when it returns true, the checker treats the argument as a
Book. Inside, check typeof value === "object", value !== null, then in and typeof for every required
property. The checker trusts the guard, so it must check everything the type promises.
Pause and try
Question 13 · Tracing
Predict exactly what this program shows. Here the checks are written as early returns instead of one && chain; the checker follows them the same way.
function describe(value: unknown): string {
if (typeof value !== "object" || value === null) {
return "not an object";
}
if (!("title" in value)) {
return "no title";
}
if (typeof value.title !== "string") {
return "title is not text";
}
return `title: ${value.title}`;
}
console.log(describe(JSON.parse('{"title": "Emma"}')));
console.log(describe(JSON.parse('{"title": 7}')));
console.log(describe(JSON.parse('{"pages": 7}')));
console.log(describe(JSON.parse("[]")));
console.log(describe(JSON.parse("null")));Check your reasoning
title: Emma
title is not text
no title
no title
not an object{"title": "Emma"}passes every check.{"title": 7}has atitle, but it is a number, so line 8 returns.{"pages": 7}is an object with notitle: line 5.[]is an array, andtypeofsays"object"for arrays, so it passes line 2; it has notitle, so line 5 returns no title, not “not an object.”nullis caught byvalue === nullon line 2.
Reread 16.8 Type Guards if any line differed.
Question 14 · Debugging
Fix isBook in guard-lies.ts so that the JSON {"title": "Emma", "pages": "474"} is rejected. Write the corrected return line and say what the program shows afterwards.
Check your reasoning
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);The original checked only that title and pages exist. Adding typeof value.title === "string" and typeof value.pages === "number" makes the guard check exactly what Book promises. With "474" as a string, isBook now returns false, the if is skipped, and the program shows nothing at all, rather than a wrong number. It is the same body as isBook in book-guard.ts.
Reread 16.8 Type Guards if you missed it.
16.9 Type Assertions with as
Sooner or later you will see code that skips the guard and writes this instead:
const book = JSON.parse(text) as Book;
as makes a type assertion: an instruction to the checker to treat a value as a certain type, without checking. It is you saying “trust me, I know what this is.” And like every TypeScript annotation, it is removed before Node runs the program, so nothing checks it at run time either.
Worked example: An assertion that is wrong
type Book = { title: string; pages: number };
const data: unknown = JSON.parse('{"name": "Dune", "pages": 412}');
const book = data as Book;
console.log(`Pages: ${book.pages}`);
console.log(book.title.toUpperCase());npx tsc reports no errors. node assert-bug.ts shows:
Pages: 412
TypeError: Cannot read properties of undefined (reading 'toUpperCase')data was honestly unknown on line 3, and line 4 threw that honesty away. The assertion told the checker it was a Book, the checker believed it, and the same crash as json-any-bug.ts came back. An assertion does not make anything true; it only stops the checker from asking.
Compare it with the guard from 16.8 on the very same data:
type Book = { title: string; pages: number };
function isBook(value: unknown): value is Book {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);
}
const data: unknown = JSON.parse('{"name": "Dune", "pages": 412}');
if (isBook(data)) {
console.log(data.title.toUpperCase());
} else {
console.log("That is not a book, so nothing was printed from it.");
}That is not a book, so nothing was printed from it.
The guard looks at the data while the program runs and answers truthfully; the assertion never looks at all.
The checker does refuse an assertion that could never be right, between two types that have no values in common:
const pages = "412" as number;
console.log(pages + 12);assert-impossible.ts:1:15 - error TS2352: Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
But notice the end of the message: it tells you how to force it anyway. And from unknown, which overlaps with everything, as is always accepted, which is exactly why it is dangerous on outside data. An assertion is also not a conversion: even if it were forced through, "412" as number would still be the string "412" when the program ran. To change a string into a number, use Day 2’s Number(). Fix or delete this file.
Key idea
value as Book tells the checker to treat a value as a Book without checking anything, at check time or run time.
If you are wrong, the program crashes later, far from the real mistake. Use a type guard for outside data.
Watch out
Thinking as converts. as number never turns a string into a number, and as Book never adds a missing title. The value is exactly what it was; only the checker’s opinion of it changes. Each time you write as, you are taking over the checker’s job, and you must be sure you are right.
Pause and try
Question 15 · Multiple choice
const data: unknown = JSON.parse('{"title": 5}'); is followed by const book = data as Book; (where Book has title: string). What happens?
npx tscrejects the assertion, becausetitleis a numbernpx tscaccepts it, andbook.titleholds"5"when the program runsnpx tscaccepts it, andbook.titleholds the number 5 when the program runsnpx tscaccepts it, andnodestops at that line with aTypeError
Check your reasoning
C. From unknown, as is always accepted, and it changes nothing at run time: title is still the number 5, while the checker now believes it is a string.
- A is wrong: the checker never looks inside the data; it cannot, because the JSON is read only when the program runs.
- B is wrong:
asdoes not convert anything. Converting isString()’s job. - D is wrong:
asis removed before Node runs the code, so that line does nothing at all at run time. A crash would come later, if the program called a string method ontitle.
Reread 16.9 Type Assertions with as if you chose differently.
16.10 Returning a Result Instead of Throwing
Throwing has one weakness you may have noticed. Read the first line of 16.1’s parseAge:
function parseAge(text: string): number;
Nothing in it says the function can throw. A caller who forgets the try gets no warning from the checker:
function parseAge(text: string): number {
const age = Number(text);
if (Number.isNaN(age)) {
throw new Error(`"${text}" is not a number`);
}
return age;
}
for (const answer of ["17", "abc", "42"]) {
console.log(`Next year you will be ${parseAge(answer) + 1}.`);
}npx tsc reports no errors, and node throw-forgotten.ts shows:
Next year you will be 18.
file:///.../day16/throw-forgotten.ts:4
throw new Error(`"${text}" is not a number`);
^
Error: "abc" is not a number
The failure is invisible in the function’s type, so the checker cannot remind anyone to handle it. There is another way: make failure part of the return type. Instead of returning a number or throwing, the function returns an object that says which of the two happened. That is a discriminated union from Day 9, with the boolean literals true and false as the discriminant, made generic with Day 14’s type parameters so it works for any kind of value:
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
A Result<number> is either { ok: true, value: 17 } or { ok: false, error: "..." }. This pattern is called a result union (or result type).
Worked example: parseAge returns a Result
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseAge(text: string): Result<number> {
const age = Number(text);
if (text.trim() === "" || Number.isNaN(age)) {
return { ok: false, error: `"${text}" is not a number` };
}
if (age < 0 || age > 130) {
return { ok: false, error: `${age} is not between 0 and 130` };
}
return { ok: true, value: age };
}
for (const answer of ["17", "abc", "-4"]) {
const result = parseAge(answer);
if (result.ok) {
console.log(`Next year you will be ${result.value + 1}.`);
} else {
console.log(`Problem: ${result.error}`);
}
}Next year you will be 18.
Problem: "abc" is not a number
Problem: -4 is not between 0 and 130| Line | What it does |
|---|---|
| 3 | The return type now says the function can fail: a Result<number> |
| 6, 9 | Failure is returned, not thrown: ok: false with a message |
| 11 | Success: ok: true with the age |
| 16 | if (result.ok) narrows on the discriminant, exactly as kind did on Day 9 |
| 17 | Only here is result.value allowed, because only the ok: true member has it |
| 19 | In the else, result is the ok: false member, so result.error is allowed |
No try, no catch, and the program never stops: every answer becomes a normal value that the loop deals with.
The real gain shows when a caller forgets to check:
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseAge(text: string): Result<number> {
const age = Number(text);
if (Number.isNaN(age)) {
return { ok: false, error: `"${text}" is not a number` };
}
return { ok: true, value: age };
}
const result = parseAge("17");
console.log(result.value + 1);result-unchecked.ts:12:20 - error TS2339: Property 'value' does not exist on type 'Result<number>'.
Property 'value' does not exist on type '{ ok: false; error: string; }'.
This is Day 9’s union message, and its second line says exactly why: the result might be the failure member, which has no value. The forgotten check that crashed throw-forgotten.ts at run time is now caught before anything runs. Fix or delete this file.
So which should you use? Both are correct tools, for different situations.
throw |
Result union | |
|---|---|---|
| Visible in the type? | No | Yes: Result<number> |
| Caller forgets to check | Crash at run time | Type error from npx tsc |
| Passes through callers | By itself, up to the nearest catch |
Each caller must check and return it on |
| Best for | Bugs and situations that should never happen | Expected failures: bad input, a missing or broken file |
A person typing abc is not a bug; it will happen every day, so a result union makes every caller deal with it. A function called with a year of 26 is a bug in the program, and throwing stops everything before the bug does more damage. Built-in functions such as JSON.parse throw, so a function that turns their throw into a result, catching inside and returning ok: false, gives you the best of both:
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
type Book = { title: string; pages: number };
function isBook(value: unknown): value is Book {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"pages" in value &&
typeof value.pages === "number"
);
}
function readBook(text: string): Result<Book> {
let data: unknown;
try {
data = JSON.parse(text);
} catch {
return { ok: false, error: "not valid JSON" };
}
if (!isBook(data)) {
return { ok: false, error: "not a book" };
}
return { ok: true, value: data };
}
for (const text of ['{"title": "Emma", "pages": 474}', "{title: Emma}", '{"title": "Emma"}']) {
const result = readBook(text);
console.log(result.ok ? `${result.value.title}, ${result.value.pages} pages` : `Skipped: ${result.error}`);
}Emma, 474 pages
Skipped: not valid JSON
Skipped: not a book
readBook deals with both risks from 16.7: line 18 may throw, and the catch turns that into a result; line 22 checks the shape with a guard. Line 16 declares data outside the try block (the 16.2 Watch Out), with the type unknown, so it can be used after the block. Every caller of readBook sees a Result<Book> and cannot forget either failure.
Key idea
A result union { ok: true; value: T } | { ok: false; error: string } puts failure into the return type, so the
checker makes every caller check result.ok before using result.value. Return results for expected failures such
as bad input; throw for bugs.
Pause and try
Question 16 · Tracing
Predict exactly what this program shows.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function divide(a: number, b: number): Result<number> {
if (b === 0) {
return { ok: false, error: "cannot divide by zero" };
}
return { ok: true, value: a / b };
}
const results = [divide(10, 4), divide(3, 0), divide(0, 3)];
for (const result of results) {
console.log(result.ok ? result.value : `Error: ${result.error}`);
}
console.log(results.filter((result) => result.ok).length);Check your reasoning
2.5
Error: cannot divide by zero
0
2divide(10, 4)is a success holding 2.5.divide(3, 0)is a failure; the conditional operator shows itserror.divide(0, 3)is a success holding 0: dividing zero is fine, andresult.okistrueeven though the value is falsy. That is why the check is onok, not onvalue.filterkeeps the two successes, so the last line shows 2.
Reread 16.10 Returning a Result Instead of Throwing if any line differed.
Question 17 · Short answer
For each function, say whether you would throw or return a result union, and why: (a) parseQuantity(text), reading what a customer typed into a quantity box; (b) average(scores), which your own code only ever calls with a non-empty array, but which would divide by zero if that ever changed.
Check your reasoning
Model answer: (a) Return a result union. Customers mistype all the time, so a bad quantity is an expected outcome, not a bug, and putting it in the return type means the checker makes every caller deal with it. (b) Throw. An empty array would mean the program itself has a bug; it should never happen, every caller would otherwise have to check for something that cannot occur, and stopping loudly makes the bug easy to find.
A complete answer must:
- match expected failures (user input) to a result union and impossible-in-a-correct-program situations (bugs) to
throw, and - give a reason for each: the result makes the checker enforce the check; the throw stops the program before a bug spreads.
Reread 16.10 Returning a Result Instead of Throwing if your reasoning differed.
Putting it together
A game club keeps a scoreboard for each day as JSON. Some days’ files are fine; some were typed by hand and are broken in different ways. This program loads each one safely and reports on it, without ever crashing. Before you type it, make sure npx tsc is clean in your day16 folder: fix or delete any broken file from today.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
type Player = { name: string; score: number };
function isPlayer(value: unknown): value is Player {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"score" in value &&
typeof value.score === "number"
);
}
function parsePlayers(text: string): Result<Player[]> {
let data: unknown;
try {
data = JSON.parse(text);
} catch {
return { ok: false, error: "not valid JSON" };
}
if (!Array.isArray(data)) {
return { ok: false, error: "expected a list of players" };
}
const items: unknown[] = data;
const players: Player[] = [];
for (const [i, item] of items.entries()) {
if (!isPlayer(item)) {
return { ok: false, error: `player ${i + 1} needs a name and a numeric score` };
}
players.push(item);
}
return { ok: true, value: players };
}
function report(label: string, text: string): void {
const result = parsePlayers(text);
if (!result.ok) {
console.log(`${label}: could not load (${result.error})`);
return;
}
const best = result.value.toSorted((a, b) => b.score - a.score).at(0);
console.log(`${label}: ${result.value.length} players, top is ${best?.name ?? "nobody"}`);
}
report("Monday", '[{"name": "Ana", "score": 12}, {"name": "Ben", "score": 19}]');
report("Tuesday", '[{"name": "Ana", "score": 15}, {"name": "Ben"}]');
report("Wednesday", '{"name": "Ana", "score": 8}');
report("Thursday", "[Ana, 8]");
report("Friday", "[]");npx tsc reports no errors, and node scoreboard.ts shows:
Monday: 2 players, top is Ben
Tuesday: could not load (player 2 needs a name and a numeric score)
Wednesday: could not load (expected a list of players)
Thursday: could not load (not valid JSON)
Friday: 0 players, top is nobody
Follow Tuesday’s text through parsePlayers:
| Line | What happens | Idea |
|---|---|---|
| 16–21 | JSON.parse succeeds, so the catch is skipped; data is unknown |
16.2, 16.7 |
| 22 | Day 6’s Array.isArray is true: it is a list |
16.8 |
| 25 | The list is stored as unknown[], so each item is unknown too |
16.6 |
| 27–31 | Player 1 passes isPlayer; player 2, {"name": "Ben"}, has no score, so the loop returns failure |
16.8 |
| 37–41 | In report, result.ok is false, so the error is shown and report returns early |
16.10 |
Wednesday’s text is valid JSON but a single object, not a list, so line 22 rejects it. Thursday’s is not JSON at all: JSON.parse throws a SyntaxError, and the catch on line 19 turns it into a result. Monday passes every check, so result.value is a Player[], and Day 11’s toSorted finds the top score. Friday’s empty list is valid, so at(0) is undefined and Day 9’s ?. and ?? give nobody.
Line 25 deserves a word. Array.isArray narrows an unknown to an array of any, the type from 16.6, so its items would not be checked. Assigning it to a variable declared unknown[] puts the checker back on duty: each item is unknown until isPlayer proves otherwise. And nothing in the program throws on purpose: every expected failure is a Result, so report cannot forget one.
Common mistakes
Today’s messages in one place. The first five come from npx tsc; the rest are what node does.
| Message or symptom | Usual cause | Fix |
|---|---|---|
TS2322: Type 'Error' is not assignable to type 'number'. |
return new Error(...) instead of throw |
throw new Error(...) |
TS2304: Cannot find name 'age'. after a try block |
A const declared inside the try block |
Use it inside the block, or declare it before with let |
TS18046: 'error' is of type 'unknown'. |
Using a caught value, or parsed JSON, without narrowing | instanceof Error, typeof, or a type guard |
TS2322: Type 'unknown' is not assignable to type 'Book'. |
Treating unknown data as a type without checking it |
Check it with a type guard first |
TS2339: Property 'value' does not exist on type 'Result<number>'. |
Using a result without checking ok |
if (result.ok) first |
TypeError: Cannot read properties of undefined after JSON.parse |
Data used as any, or asserted with as, had a different shape |
Store it as unknown and use a type guard |
SyntaxError from JSON.parse |
The text is not valid JSON | Catch it and report it |
An error report says Error: instead of your class name |
The custom class did not set this.name |
this.name = "AgeError"; in the constructor |
| Every error handled as “a bug” | instanceof Error checked before instanceof AgeError |
Check the most specific class first |
A wrong answer such as 47412, no error at all |
A type guard that checked a property exists but not its type | Add a typeof check for every property |
Vocabulary
| Term | Definition | Example |
|---|---|---|
throw |
Stops the current function and reports a problem to its callers | throw new Error("Bad age"); |
| error object | An object made from Error or a subclass, with a name and a message |
new Error("The tank is empty") |
message |
The text describing what went wrong | error.message |
name |
The kind of error, shown before the colon in a report | "Error", "AgeError" |
try / catch |
Runs the try block; if it throws, runs the catch block instead and carries on |
try { ... } catch (error) { ... } |
| caught / uncaught | Received by a catch block / reaching the top and stopping the program |
An uncaught error shows a report |
finally |
A block that runs after try and catch every time |
finally { console.log("Door locked"); } |
unknown |
The type of a value that could be anything; must be narrowed before use | const data: unknown = JSON.parse(text); |
instanceof |
true when an object was made from a class or one of its subclasses; narrows the type |
error instanceof Error |
| custom error class | A class that extends Error, so callers can pick its errors out |
class AgeError extends Error |
| rethrowing | Throwing a caught value again from a catch block, to pass on what you cannot handle |
throw error; |
any |
The type that turns checking off for a value | let reading: any = 42; |
| JSON | A text format for data that looks like object and array literals, with double quotes | {"title": "Dune", "pages": 412} |
JSON.parse |
Turns JSON text into values; returns any; throws SyntaxError for bad text |
JSON.parse("[1, 2]") |
JSON.stringify |
Turns a value into JSON text | JSON.stringify([1, 2]) is "[1,2]" |
| type guard | A function that checks a value and tells the checker its type with a type predicate | function isBook(value: unknown): value is Book |
| type predicate | The return type value is Book: when the function returns true, value is a Book |
value is Book |
| type assertion | as: telling the checker to treat a value as a type, with no check at all |
data as Book |
| result union | A return type that holds either a success with a value or a failure with an error | { ok: true; value: T } | { ok: false; error: string } |
Summary
throw new Error("message")stops a function that cannot do its job. The error travels up through its callers until atry/catchreceives it; if none does, the program stops with the message. Afinallyblock runs at the end every time, for clean-up.- JavaScript can throw anything, so a caught value is
unknown. Narrow it withinstanceof Error; give your own failures a custom error class (withthis.nameset) so callers can pick them out, handle them, and rethrow the rest. anyturns checking off and lets mistakes through to run time;unknownkeeps checking on.JSON.parsereturnsanyand throwsSyntaxErrorfor bad text, so store its result asunknown.- A type guard (
value is Book) checks every required property’s presence and type and then lets the checker treat the value as aBook. A type assertion (as Book) checks nothing, so a wrong one crashes later; prefer the guard for outside data. - A result union (
{ ok: true; value: T } | { ok: false; error: string }) puts failure in the return type, so the checker makes callers checkok. Use it for expected failures such as bad input, and throw for bugs.
Practice
Do these in your day16 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as return-error.ts, try-scope.ts, catch-message-wrong.ts, unknown-safe.ts, json-unknown.ts, narrow-skip.ts, assert-impossible.ts, result-unchecked.ts, or the review question’s review-any.ts), fix it or delete it. Then type each program yourself, check it with npx tsc, run it with node, and only then open the answer.
Question 18 · Short answer
parseAge that throws. Write parseAge(text: string): number that throws a clear error when the text is not a number, and when it is not a whole number from 0 to 130. Write a caller that reads each age typed after the file name on the command line (Day 13’s process.argv), catches the error, and reports it, so one bad age does not stop the others. Run it as node parse-age.ts 17 seventeen 150 -3 12.5 0. (Number.isInteger(value) is true only for a whole number.)
Check your reasoning
One possible solution:
class AgeError extends Error {
constructor(message: string) {
super(message);
this.name = "AgeError";
}
}
/** Reads a whole-number age from 0 to 130, or throws an AgeError. */
function parseAge(text: string): number {
const age = Number(text);
if (text.trim() === "" || Number.isNaN(age)) {
throw new AgeError(`"${text}" is not a number`);
}
if (!Number.isInteger(age) || age < 0 || age > 130) {
throw new AgeError(`${age} is not a whole number from 0 to 130`);
}
return age;
}
for (const text of process.argv.slice(2)) {
try {
const age = parseAge(text);
console.log(`${age}: ok`);
} catch (error) {
if (error instanceof AgeError) {
console.log(`Rejected: ${error.message}`);
} else {
throw error;
}
}
}17: ok
Rejected: "seventeen" is not a number
Rejected: 150 is not a whole number from 0 to 130
Rejected: -3 is not a whole number from 0 to 130
Rejected: 12.5 is not a whole number from 0 to 130
0: okprocess.argv.slice(2) skips the two entries for node and the file, as on Day 13, leaving the six ages as strings. parseAge throws an AgeError for each problem; the empty-text check is there because Number("") is 0, which would otherwise be accepted. The caller’s try block holds the call and the line that uses its result, the catch narrows with instanceof AgeError, and anything else is rethrown, because it would be a bug. A plain Error and instanceof Error would also be a correct answer. The doc comment from Day 8 says what the function throws, since its type cannot.
Reread 16.2 Catching with try and catch and 16.5 Custom Error Classes if your result differed.
Question 19 · Short answer
A guard for a list of books. A Book has a title (string), pages (number), and an optional subtitle (string). Write isBook and isBookList(value: unknown): value is Book[], and test the list guard on parsed JSON: a good list, a list with one book missing its pages, a book whose subtitle is a number, a single book that is not in a list, and an empty list. For each valid list, show how many books and pages it has.
Check your reasoning
One possible solution:
type Book = { title: string; pages: number; subtitle?: string };
function isBook(value: unknown): value is Book {
if (typeof value !== "object" || value === null) {
return false;
}
if (!("title" in value) || typeof value.title !== "string") {
return false;
}
if (!("pages" in value) || typeof value.pages !== "number") {
return false;
}
if ("subtitle" in value && typeof value.subtitle !== "string") {
return false;
}
return true;
}
function isBookList(value: unknown): value is Book[] {
return Array.isArray(value) && value.every((item: unknown) => isBook(item));
}
const shelves = [
'[{"title": "Dune", "pages": 412}, {"title": "Emma", "pages": 474, "subtitle": "A Novel"}]',
'[{"title": "Dune", "pages": 412}, {"title": "Emma"}]',
'[{"title": "Dune", "pages": 412, "subtitle": 2}]',
'{"title": "Dune", "pages": 412}',
"[]",
];
for (const text of shelves) {
const data: unknown = JSON.parse(text);
if (isBookList(data)) {
const pages = data.reduce((sum, book) => sum + book.pages, 0);
console.log(`${data.length} books, ${pages} pages`);
} else {
console.log("Not a list of books");
}
}2 books, 886 pages
Not a list of books
Not a list of books
Not a list of books
0 books, 0 pagesisBook uses early returns, one per rule, which is easier to read than one long && chain once there are optional properties. An optional property may be missing, so it is checked only if it is there: "subtitle" in value && typeof value.subtitle !== "string" rejects a subtitle that is present but not a string. isBookList first checks Array.isArray, then uses Day 11’s every to check each item. The callback’s parameter is annotated unknown because Array.isArray narrows to an array of any (see Putting it together). After isBookList(data) is true, data is a Book[], so reduce can add up book.pages. An empty list is a valid list of books: every is true for an empty array.
Reread 16.8 Type Guards if your result differed.
Question 20 · Short answer
parseAge that returns a result. Rewrite exercise 18 so that parseAge returns a Result<number> instead of throwing, and rewrite the caller to match. Run it with the same ages. Then compare the two callers: what does each one have to remember, and what happens if it forgets?
Check your reasoning
One possible solution:
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
/** Reads a whole-number age from 0 to 130. */
function parseAge(text: string): Result<number> {
const age = Number(text);
if (text.trim() === "" || Number.isNaN(age)) {
return { ok: false, error: `"${text}" is not a number` };
}
if (!Number.isInteger(age) || age < 0 || age > 130) {
return { ok: false, error: `${age} is not a whole number from 0 to 130` };
}
return { ok: true, value: age };
}
for (const text of process.argv.slice(2)) {
const result = parseAge(text);
if (result.ok) {
console.log(`${result.value}: ok`);
} else {
console.log(`Rejected: ${result.error}`);
}
}node parse-age-result.ts 17 seventeen 150 -3 12.5 0 shows the same six lines as exercise 18:
17: ok
Rejected: "seventeen" is not a number
Rejected: 150 is not a whole number from 0 to 130
Rejected: -3 is not a whole number from 0 to 130
Rejected: 12.5 is not a whole number from 0 to 130
0: okComparison. The throwing caller must remember to wrap the call in try / catch and to narrow the unknown error; if it forgets the try, the checker says nothing and the first bad age stops the program. The result caller must check result.ok; if it forgets, result.value is a type error (TS2339), so the mistake is caught before the program runs. The result version is also shorter here: no instanceof, no rethrow, and no custom class, because the failure is an ordinary value. The throwing version would be the better fit if a bad age meant a bug rather than a typing mistake.
Reread 16.10 Returning a Result Instead of Throwing if your reasoning differed.
Review questions
Question 21 · Tracing
Predict exactly what this program shows. Watch the finally block, and remember that stock.get gives undefined for a key that is not in the map.
class StockError extends Error {
constructor(message: string) {
super(message);
this.name = "StockError";
}
}
function take(item: string, stock: Map<string, number>): void {
const count = stock.get(item);
if (count === undefined) {
throw new Error(`unknown item ${item}`);
}
if (count === 0) {
throw new StockError(`${item} sold out`);
}
stock.set(item, count - 1);
}
const stock = new Map([
["pen", 1],
["pad", 0],
]);
for (const item of ["pen", "pen", "pad", "ink"]) {
try {
take(item, stock);
console.log(`took ${item}`);
} catch (error) {
if (error instanceof StockError) {
console.log(`sorry, ${error.message}`);
} else if (error instanceof Error) {
console.log(`bug: ${error.message}`);
}
} finally {
console.log(`${item} left: ${stock.get(item) ?? "none"}`);
}
}Check your reasoning
took pen
pen left: 0
sorry, pen sold out
pen left: 0
sorry, pad sold out
pad left: 0
bug: unknown item ink
ink left: none- First
"pen": the count is 1, so it becomes 0 and took pen shows;finallyshows 0 left. - Second
"pen": the count is now 0, so aStockErroris thrown; the firstinstanceofmatches.finallystill runs. "pad": 0 from the start, the same path."ink": not in the map, so a plainErroris thrown. It is not aStockError, so the second check (instanceof Error) handles it.finallyruns, andstock.get("ink")isundefined, so??gives none.
The checks are in the right order: the subclass first, then Error.
Reread 16.3 Cleaning Up with finally and 16.5 Custom Error Classes if any line differed.
Question 22 · Multiple choice
Here is a program that npx tsc rejects on exactly one line:
const fromAny: any = JSON.parse('{"count": 3}');
const fromUnknown: unknown = JSON.parse('{"count": 3}');
const a: number = fromAny.count;
const b: number = fromAny.cuont;
const c: number = fromUnknown.count;
const d = typeof fromUnknown === "object" && fromUnknown !== null && "count" in fromUnknown;
console.log(a, b, c, d);Which line, and what does that tell you about line 5?
- Line 4, because
countmight not exist - Line 5, because
cuontis misspelled - Line 6, because
fromUnknownmust be narrowed first; line 5’s typo is accepted, becausefromAnyisany - Line 7, because
incannot be used onunknown
Check your reasoning
C. The checker reports review-any.ts:6:19 - error TS18046: 'fromUnknown' is of type 'unknown'. and nothing else. Line 5 reads a misspelled property from an any and puts it in a number variable, and the checker lets it through: at run time, b would be undefined.
- A is wrong:
anyallows any property, so the checker does not ask whethercountexists. - B is wrong, and that is the lesson:
anyhides typos too. - D is wrong: line 7 narrows step by step,
typeof,!== null, thenin, which is exactly the type guard recipe.
Reread 16.6 any Versus unknown and 16.8 Type Guards if you chose differently.
Question 23 · Debugging
npx tsc accepts this program, but node stops with an error. Name the error, explain why the checker missed it, and fix the program so that broken settings fall back to defaults of volume 50 and theme "light".
type Settings = { volume: number; theme: string };
const saved = '{"volume": "80", "theme": "dark"}';
const settings = JSON.parse(saved) as Settings;
console.log(`Theme: ${settings.theme}`);
console.log(`Volume: ${settings.volume.toFixed(0)}%`);Check your reasoning
node review-settings.ts shows Theme: dark and then stops with:
TypeError: settings.volume.toFixed is not a functionThe saved JSON has "volume": "80", a string. Line 4’s as Settings told the checker the data was a Settings without checking, so it believed volume was a number and accepted toFixed. At run time it is a string, and strings have no toFixed. The fix stores the parsed value as unknown and checks it with a type guard:
type Settings = { volume: number; theme: string };
function isSettings(value: unknown): value is Settings {
return (
typeof value === "object" &&
value !== null &&
"volume" in value &&
typeof value.volume === "number" &&
"theme" in value &&
typeof value.theme === "string"
);
}
const defaults: Settings = { volume: 50, theme: "light" };
const saved = '{"volume": "80", "theme": "dark"}';
const data: unknown = JSON.parse(saved);
const settings = isSettings(data) ? data : defaults;
console.log(`Theme: ${settings.theme}`);
console.log(`Volume: ${settings.volume.toFixed(0)}%`);Theme: light
Volume: 50%isSettings checks both properties and their types, so the string volume makes it return false, and the conditional operator picks defaults. Both output lines come from the defaults: the guard rejects the saved settings as a whole, so the saved theme is not used either.
Reread 16.9 Type Assertions with as and 16.8 Type Guards if you missed it.
Question 24 · Multiple choice
A function begins function load(text: string): Result<Book> and calls JSON.parse(text). Which body handles both ways the text can be bad, and never throws?
- Call
JSON.parseinsidetry; incatch, return{ ok: false, error: "not valid JSON" }; then return{ ok: true, value: data as Book } - Call
JSON.parseinsidetry; incatch, return{ ok: false, error: "not valid JSON" }; then return failure unlessisBook(data), and success otherwise - Return failure unless
isBook(JSON.parse(text)), and success otherwise, with notry - Call
JSON.parseinsidetry; incatch, rethrow the error; then return success ifisBook(data)
Check your reasoning
B. Text that is not JSON makes JSON.parse throw, which the catch turns into a failure; JSON with the wrong shape is caught by the guard. This is readBook from 16.10.
- A is wrong:
as Bookchecks nothing, so JSON with the wrong shape is reported as a success. - C is wrong: without a
try, invalid JSON throws aSyntaxErrorout ofload, and the caller, trusting theResulttype, has nocatch. - D is wrong: rethrowing means
loadcan throw after all, and it also has no failure result for the wrong shape.
Reread 16.7 JSON.parse Returns any and 16.10 Returning a Result Instead of Throwing if you chose differently.
Question 25 · Short answer
Sam’s program reads a list of players from a file and works fine with today’s file. Sam says: “JSON.parse(text) as Player[] is one line and it works. Why write a type guard?” Give two reasons, each tied to something that can actually happen at run time.
Check your reasoning
Model answer: First, the file can change: someone edits it by hand, or an older version of the program wrote it with different property names. With as, nothing checks the data, so the program would crash with a TypeError far from the real problem, or, worse, quietly compute a wrong answer such as "474" + 12 being "47412". A guard checks the data every time the program runs and lets you report the problem clearly. Second, as turns off the checker exactly where it is most useful: from then on, every line trusts the data, and the checker has no way to warn about a missing check. With unknown and a guard, the checker forces the check and narrows the type only where it has been proven.
A complete answer gives two reasons, such as:
- an assertion is not checked at run time, so data with the wrong shape causes a crash or a wrong answer later, and
- the guard runs on the real data every time and lets the program report or skip bad data instead, or
as(likeany) makes the checker trust what it has not seen, whileunknownplus a guard keeps the checker working.
Reread 16.9 Type Assertions with as if your reasoning differed.
Go further
MDN’s guide covers throw, try, catch, finally, and the built-in error types: MDN: Control flow and error handling, exception handling statements. The Handbook’s narrowing page has a section on type guards written with value is Type: TypeScript Handbook: Using type predicates.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can throw an Error with a clear message and read the report Node shows when nobody catches it. Reread
- I can predict which lines run when code in a try block throws, including through several function calls. Reread
- I can use finally for clean-up and say when it runs. Reread
- I can explain why a caught value is unknown and narrow it with instanceof Error. Reread
- I can write a custom error class, check for it first, and rethrow errors I cannot handle. Reread
- I can explain the difference between any and unknown and say which one to use. Reread
- I can read JSON with JSON.parse into unknown and handle a SyntaxError. Reread
- I can write a type guard that checks every property of a type. Reread
- I can explain why an as assertion hides bugs and what to use instead. Reread
- I can return a result union instead of throwing and decide which of the two a function should use. Reread