typescript · level 3 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Return a result so callers cannot forget the failure.
Some calls fail: JSON.parse throws on broken text. runs the try block and, if anything throws, jumps to the catch block instead of crashing. The error it catches is unknown, because anything can be thrown, so check it before you use it.
A thrown error is invisible in a function's type, so callers forget it. A makes failure part of the return type: a discriminated union of { ok: true; value: T } and { ok: false; error: string }. Callers must check ok before they can reach the value.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function parseJson(text: string): Result<unknown> {
try {
return { ok: true, value: JSON.parse(text) };
} catch {
return { ok: false, error: `Not valid JSON: ${text}` };
}
}
console.log(parseJson('{"cups": 2}'));
console.log(parseJson("{cups: 2}")); If you do not need the error, write catch with no brackets after it.
guess first
Share the sweets. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function share(sweets: number, people: number): Result<number> {
if (people === 0) {
return { ok: false, error: "Nobody to share with" };
}
return { ok: true, value: sweets / people };
}
const each = share(12, 3);
console.log(each.value);
your turn
Your turn. Turn an answer into an age.
Fill in ok for the failure and for the success, then type an age as text.
fix it
The JSON checker will not build. Fix the catch.
- Read the error:
TS18046sayseis of typeunknown. - Anything can be thrown, even a number, so
emight have noname. Narrow it first. - Wrap the return in
if (e instanceof Error) { ... }and return"invalid"after it.
nailed it
your failures are part of the plan now. :D
try...catchturns a crash into code you control.- The caught error is
unknown, so narrow it before use. - A Result type makes callers check
okbefore the value.
new words in your collection
- try...catch
- Result type
This lesson isn’t saved. A free account remembers every lesson you finish.