TypeScript, lesson 9
When something goes wrong at run time, such as bad input, a missing item or a broken JSON message, TypeScript programs use JavaScript's exceptions. TypeScript adds one important twist to how you catch them, and it also makes a second style of error handling practical: returning errors as ordinary, typed values.
throw stops the current function and jumps to the nearest enclosing catch, skipping
everything in between. finally runs whether or not an error happened, which makes it the
place for cleanup. Built-in error classes include Error, TypeError, RangeError and
SyntaxError (thrown by ).
2 exercises to try what you just read.
JSON.parseunknownJavaScript lets you throw anything, even a string or a number. So TypeScript cannot
promise that err is an Error; in strict mode its type is unknown. You must narrow it
before using it:
instanceof checks the class of an object at run time and narrows the type at the same time.
This also lets you handle the errors you expect and rethrow the rest with throw err;.
Extending Error gives your errors a name and extra typed data:
When you wrap a low-level error in a higher-level one, keep the original:
throw new Error("could not load settings", { cause: err });.
Exceptions are invisible in a function's type: parseAge(text: string): number does not tell
callers it can throw. An alternative is to return either a success or a failure, described
by a union type:
The ok property is a discriminant: checking it narrows r to one side of the union. The
caller cannot forget about the failure case, because r.value is a type error until ok has
been checked. (<T> makes Result work for any value type; generics get their own lesson.)
A good rule of thumb: throw for truly unexpected problems and programmer mistakes; return a result when failure is a normal, expected outcome, such as invalid user input.
A settings file has one key=value pair per line. Write parseLine(line: string, lineNo: number): [string, number] that returns the key and the numeric value, and throws a
ConfigError (a class you write, extending Error, with a line: number property) when:
=: message missing =;=, trimmed) is empty: message empty key;=, trimmed) is not a number or is empty: message
bad number.The main program, which is given, ignores blank lines, prints KEY = VALUE for good lines and
line N: MESSAGE for bad ones, and finally prints N settings loaded.
Sample input:
volume = 7
brightness=
=3
speed 4Sample output:
volume = 7
line 2: bad number
line 3: empty key
line 4: missing =
1 settings loadedEach input line is a calculation A OP B where OP is +, -, * or /. Write a function
calculate(line: string): Result<number> that never throws. It returns
{ ok: false, error: ... } with one of these messages:
expected 3 parts when the line does not split into exactly three parts;not a number when A or B is not a number;unknown operator when OP is something else;division by zero when dividing by 0.Otherwise it returns { ok: true, value: ... }. For each line, print the value (rounded to
at most two decimals, so 10 / 4 prints 2.5 and 1 / 3 prints 0.33) or error: MESSAGE.
Sample input:
10 / 4
7 % 2
3 / 0Sample output:
2.5
error: unknown operator
error: division by zeroTo round to at most two decimals, use Math.round(x * 100) / 100.
function parseAge(text: string): number {
const age = Number(text);
if (!Number.isInteger(age) || age < 0) {
throw new RangeError(`invalid age: ${text}`);
}
return age;
}
try {
console.log(parseAge("41"));
console.log(parseAge("-3")); // throws; the next line never runs
console.log("unreachable");
} catch (err) {
console.log("caught a problem");
} finally {
console.log("finally always runs");
}try {
JSON.parse("{oops");
} catch (err) {
if (err instanceof Error) {
console.log(`${err.name}: ${err.message}`); // err is Error here
} else {
console.log("something odd was thrown");
}
}class ValidationError extends Error {
field: string;
constructor(field: string, message: string) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email", "missing @");
} catch (err) {
if (err instanceof ValidationError) {
console.log(`${err.field}: ${err.message}`); // email: missing @
}
}type Result<T> = { ok: true; value: T } | { ok: false; error: string };
function safeDivide(a: number, b: number): Result<number> {
if (b === 0) return { ok: false, error: "division by zero" };
return { ok: true, value: a / b };
}
const r = safeDivide(10, 4);
if (r.ok) {
console.log(r.value); // TypeScript knows value exists here
} else {
console.log(r.error); // and error exists here
}