Sub topic 5
Errors: why catch gives you unknown
This chapter explains why the variable in a catch clause has type unknown, how to narrow it safely, and where TypeScript's help on errors ends. It assumes you know basic TypeScript types, union types and narrowing, and async/await. It also assumes you have seen try/catch in JavaScript.
What the type system knows about errors
A function signature describes what a function returns. It says nothing about what the function throws. TypeScript has no throws clause, so these two functions have the same kind of type:
function parsePort(text: string): number {
const n = Number(text);
if (!Number.isInteger(n)) {
throw new RangeError(`Not an integer: ${text}`);
}
return n;
}
async function readPort(text: string): Promise<number> {
return parsePort(text);
}parsePort is typed (text: string) => number, and the RangeError appears nowhere in that type. In readPort, a throw becomes a rejected promise. The type Promise<number> describes only the fulfilled case. The rejection reason has no type position at all.
Why JavaScript forces unknown
In JavaScript, throw accepts any value, not only Error objects. All of these are legal:
function throwSomething(kind: number): never {
if (kind === 0) throw new Error("an Error");
if (kind === 1) throw "a string";
if (kind === 2) throw { code: 42 };
if (kind === 3) throw undefined;
throw null;
}Even if your own code only throws Error objects, the try block may call a library, a callback, or a getter that throws something else. Some runtimes also raise their own objects, such as a DOMException from fetch aborts. The compiler cannot know which value arrives, so the honest type for the caught value is unknown: it could be anything, and you must check before using it.
The strict flag behind it
Since TypeScript 4.4, the useUnknownInCatchVariables option makes catch variables unknown. The strict option turns it on. Older code, or projects with strict off, get any, which lets you write err.message with no check. That compiles, and it crashes at runtime if err is undefined or a string.
| Setting | Type of `err` in `catch (err)` |
|---|---|
| `strict: true` (or `useUnknownInCatchVariables: true`) | `unknown` |
| `useUnknownInCatchVariables: false` | `any` |
| Explicit `catch (err: unknown)` | `unknown`, in any configuration |
| Explicit `catch (err: any)` | `any`, in any configuration |
| Explicit `catch (err: Error)` | Compile error, because only `any` and `unknown` are allowed |
The last row matters. TypeScript refuses catch (err: Error) because it would be an unchecked claim about a value the compiler cannot verify. Writing catch (err: unknown) explicitly is a good habit even under strict. It documents the intent and keeps the code correct if the config changes.
How a rejection reaches catch
Inside an async function, await on a rejected promise throws the rejection reason at the await expression. A catch clause around that expression receives the value.
Narrowing with instanceof
The standard pattern is to narrow with instanceof Error, handle what you understand, and rethrow the rest.
async function run(task: () => Promise<void>): Promise<void> {
try {
await task();
} catch (err) {
if (err instanceof Error) {
console.error(err.message);
} else {
throw err;
}
}
}Inside the if, err has type Error, so message, name, and stack are available. In the else branch, err is still unknown. Rethrowing it avoids silently swallowing a surprising value. Swallowing is the most common mistake in catch blocks, because it hides bugs.
Normalizing to an Error
If many catch blocks need an Error, write the conversion once.
function toError(value: unknown): Error {
if (value instanceof Error) {
return value;
}
if (typeof value === "string") {
return new Error(value);
}
return new Error(`Non-error value thrown: ${String(value)}`);
}
async function runLogged(task: () => Promise<void>): Promise<void> {
try {
await task();
} catch (err) {
const error = toError(err);
console.error(error.name, error.message);
}
}This is the right choice when you only need to log or display the failure. It is the wrong choice when the decision depends on what the value was, for example whether it was a 404. In that case, narrow to the specific type instead of flattening it.
Custom error classes
To branch on kinds of failure, define error classes and narrow with instanceof. The class carries typed fields that a plain Error does not have.
class HttpError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
this.name = "HttpError";
}
}
async function getText(url: string): Promise<string> {
const res = await fetch(url);
if (!res.ok) {
throw new HttpError(res.status, `HTTP ${res.status}`);
}
return res.text();
}
async function loadOrNull(url: string): Promise<string | null> {
try {
return await getText(url);
} catch (err) {
if (err instanceof HttpError && err.status === 404) {
return null;
}
throw err;
}
}Only the 404 case is handled. Every other failure, including network errors and 500 responses, propagates to the caller. Two gotchas apply to this pattern:
- If your compile target is ES5, subclasses of
Errorlose their prototype chain, andinstanceof HttpErrorcan befalse. Use an ES2015 or newer target. - Error classes are matched by identity. If two copies of the same package are installed, or the error crosses a realm boundary such as an iframe or a Node
vmcontext,instanceoffails even though the shapes match.
Narrowing by shape
When instanceof is unreliable, check the shape of the value with a type guard. Node's system errors are a common case, because they carry a string code such as "ENOENT".
function hasCode(value: unknown): value is { code: string } {
return (
typeof value === "object" &&
value !== null &&
"code" in value &&
typeof value.code === "string"
);
}
async function readOptional(
read: () => Promise<string>,
): Promise<string | undefined> {
try {
return await read();
} catch (err) {
if (hasCode(err) && err.code === "ENOENT") {
return undefined;
}
throw err;
}
}The expression "code" in value narrows value to an object with a code property of type unknown (TypeScript 4.9 and later). That is why typeof value.code === "string" compiles without a cast. A type guard like this is still a promise you make to the compiler. If the body of hasCode is wrong, the compiler trusts it anyway, so keep guards small and test them.
Three places where errors escape your types
The callback in .catch is any
The Promise.prototype.catch method declares its callback parameter as any, regardless of strict. The same applies to the reject function of new Promise. The compiler therefore does not protect you here, and you must annotate the parameter yourself.
async function getTextOrEmpty(url: string): Promise<string> {
return getText(url).catch((reason: unknown) => {
console.error(toError(reason).message);
return "";
});
}Without the : unknown annotation, reason is any, and reason.message would compile.
A missing await skips the catch
A try block catches only what is thrown while it runs. If you return a promise without awaiting it, the function exits before the promise settles, and the rejection arrives after the catch has gone out of scope.
async function brokenFallback(url: string): Promise<string> {
try {
return getText(url); // rejection bypasses the catch
} catch {
return "fallback";
}
}
async function workingFallback(url: string): Promise<string> {
try {
return await getText(url); // rejection is caught here
} catch {
return "fallback";
}
}Both versions have the same type, Promise<string>, so the compiler does not warn you. The @typescript-eslint/return-await rule with the in-try-catch option detects this, and a later chapter on floating promises covers the related lint rules.
The catch is too wide
A try block that wraps ten statements catches errors from all ten, and you cannot tell which one failed. Keep the guarded region small, and catch only where you can do something useful: retry, fall back, translate to a domain error, or report.
class ConfigError extends Error {
constructor(message: string, options?: { cause?: unknown }) {
super(message, options);
this.name = "ConfigError";
}
}
async function loadConfigText(url: string): Promise<string> {
try {
return await getText(url);
} catch (err) {
throw new ConfigError("Could not load configuration", { cause: err });
}
}The cause option keeps the original error attached for debugging. It requires lib set to ES2022 or newer, and the value you read back from error.cause is unknown, so you narrow it the same way.
Rules of thumb
- Leave
stricton, and writecatch (err: unknown)if you want the intent visible. - Narrow before use. Prefer
instanceoffor classes you own and shape-checking guards for values from outside your code. - Handle only what you recognise, and rethrow everything else.
- Annotate
.catchcallbacks withunknown. - Use
return awaitinsidetryblocks when you want the catch to apply. - Treat the return type as covering only success. If failure must be visible in the type, model it explicitly, which a later chapter on Result unions covers.
Exercise
A teammate writes catch (e: Error) { console.error(e.message); } in a strict project. What happens, and what is the smallest correct fix?
Show answer
The compiler rejects it with an error that a catch clause variable annotation must be any or unknown, because it cannot verify that the thrown value is an Error. The fix is catch (e: unknown) (or no annotation), followed by if (e instanceof Error) { console.error(e.message); } else { throw e; }.
Exercise
This function is typed Promise<string>, yet when getText rejects, the caller sees the rejection instead of "fallback". Why, and how do you fix it?
async function load(url: string): Promise<string> {
try {
return getText(url);
} catch {
return "fallback";
}
}
Show answer
The promise is returned without await, so the function leaves the try block before the promise settles, and the rejection occurs outside the catch. Change return getText(url); to return await getText(url); so the rejection is rethrown inside the try block and caught.
Exercise
Write a type guard isAbortError(value: unknown): value is { name: "AbortError" } that returns true for any object whose name property is the string "AbortError". Why might this be preferable to instanceof DOMException in code that runs in several environments?
Show answer
Implementation: function isAbortError(value: unknown): value is { name: "AbortError" } { return typeof value === "object" && value !== null && "name" in value && value.name === "AbortError"; }. A shape check works across realms and runtimes, where DOMException may not exist as a global, may be a different class, or may come from another copy of a library, all of which make instanceof return false for a real abort error.