TypeScript Error Handling
TypeScript uses JavaScript's error machinery unchanged: you throw errors and handle them with try...catch...finally. What TypeScript adds is a careful view of what an error might be — and some patterns that make failures part of a function's type, so callers can't forget about them.
catch variables are unknown
JavaScript lets you throw anything: an Error, a string, a number, even undefined. So in strict mode the variable in catch (err) has type unknown, and TypeScript won't let you use err.message until you have checked what err is:
function parseAge(text: string): number {
const n = Number(text);
if (!Number.isInteger(n) || n < 0) {
throw new Error(`"${text}" is not a valid age`);
}
return n;
}
try {
parseAge("abc");
} catch (err) {
console.log(err.message);
}main.ts(12,15): error TS18046: 'err' is of type 'unknown'.
Narrow it with instanceof first. A small helper keeps this tidy across a code base:
function parseAge(text: string): number {
const n = Number(text);
if (!Number.isInteger(n) || n < 0) {
throw new Error(`"${text}" is not a valid age`);
}
return n;
}
function errorMessage(err: unknown): string {
if (err instanceof Error) return err.message;
return String(err);
}
for (const input of ["42", "abc", "-3"]) {
try {
console.log("age:", parseAge(input));
} catch (err) {
console.log("error:", errorMessage(err));
} finally {
console.log("checked", input);
}
}age: 42
checked 42
error: "abc" is not a valid age
checked abc
error: "-3" is not a valid age
checked -3
Note:
finallyruns whether thetryblock succeeded or threw — use it for cleanup like closing files or hiding a loading spinner.
Custom error classes
Extending Error lets you attach extra, typed data and tell different failures apart with instanceof. Setting name makes logs clearer:
class ValidationError extends Error {
constructor(public field: string, message: string) {
super(message);
this.name = "ValidationError";
}
}
class NotFoundError extends Error {
name = "NotFoundError";
constructor(public id: number) {
super(`item ${id} does not exist`);
}
}
function handle(fn: () => void) {
try {
fn();
} catch (err) {
if (err instanceof ValidationError) {
console.log(`${err.name} on '${err.field}': ${err.message}`);
} else if (err instanceof NotFoundError) {
console.log(`${err.name}: id=${err.id}`);
} else {
throw err; // not ours — let it propagate
}
}
}
handle(() => { throw new ValidationError("email", "must contain @"); });
handle(() => { throw new NotFoundError(404); });ValidationError on 'email': must contain @
NotFoundError: id=404
ES2022 also added the cause option, which keeps the original error when you wrap it in a more meaningful one: new Error("could not load settings", { cause: err }).
never and exhaustive checks
A function that always throws never returns normally, so its return type is never. TypeScript uses that information for control flow: after a never call the code is unreachable, so ?? fail(...) removes undefined from a type:
function fail(message: string): never {
throw new Error(message);
}
function getPort(env: Record<string, string | undefined>): number {
const raw = env.PORT ?? fail("PORT is not set"); // raw: string
return Number.parseInt(raw, 10);
}
console.log(getPort({ PORT: "8080" }));
try {
getPort({});
} catch (err) {
console.log((err as Error).message);
}8080
PORT is not set
never also powers exhaustive checks. In the default branch of a switch over a union, every handled member has been narrowed away. Assigning what is left to a never variable compiles only if nothing is left — so when someone adds a new member to the union, the compiler points at every switch that forgot it:
type Shape =
| { kind: "circle"; r: number }
| { kind: "square"; side: number }
| { kind: "triangle"; base: number; h: number };
function area(s: Shape): number {
switch (s.kind) {
case "circle": return Math.PI * s.r ** 2;
case "square": return s.side ** 2;
default: {
const unhandled: never = s;
throw new Error(`unhandled shape: ${JSON.stringify(unhandled)}`);
}
}
}main.ts(11,13): error TS2322: Type '{ kind: "triangle"; base: number; h: number; }' is not assignable to type 'never'.
Adding case "triangle": return (s.base * s.h) / 2; fixes it.
Errors as values: the Result pattern
Exceptions are invisible in a function's signature — nothing in parseAge(text: string): number warns you it may throw. For expected failures (bad input, item not found) many TypeScript projects return a result object instead. The discriminated union makes the caller check ok before touching the value:
type Result<T, E = string> =
| { ok: true; value: T }
| { ok: false; error: E };
function safeDivide(a: number, b: number): Result<number> {
if (b === 0) return { ok: false, error: "division by zero" };
return { ok: true, value: a / b };
}
for (const [a, b] of [[10, 4], [1, 0]]) {
const r = safeDivide(a, b);
if (r.ok) {
console.log(`${a} / ${b} = ${r.value}`);
} else {
console.log(`${a} / ${b} failed: ${r.error}`);
}
}10 / 4 = 2.5
1 / 0 failed: division by zero
| Approach | Best for |
|---|---|
throw + try/catch |
unexpected failures, bugs, things that should stop the operation |
Result<T, E> return value |
expected, recoverable failures the caller must handle |
T | undefined return |
"not found" when no extra error detail is needed |
Tip: Only throw
Errorobjects (or subclasses), never strings. They carry a stack trace, andinstanceof Errorchecks in catch blocks keep working.
Test yourself
In strict mode, what is the type of err in catch (err)?
Erroranyunknownnever
What is the return type of a function that always throws?
voidundefinedneverError
Why might you return a Result<T, E> instead of throwing?
- It is faster
- The possible failure becomes part of the type, so callers must handle it
- Exceptions don't work in TypeScript
- It hides errors from the user