TypeScript "error is of type 'unknown'" in catch Blocks: Why It Happens and How to Handle It
Why TypeScript says error is of type unknown in catch blocks, and how to handle it with instanceof Error, type guards, Error.cause and a small toError helper.
TypeScript reports 'error' is of type 'unknown' (TS18046) inside a catch block because the strict flag turns on useUnknownInCatchVariables, which types the caught value as unknown instead of any. JavaScript lets you throw anything, so TypeScript can't promise it's an Error. The fix is to check before you use it, most often with if (error instanceof Error).
try {
JSON.parse("{");
} catch (error) {
console.log(error.message);
// ~~~~~ 'error' is of type 'unknown'. ts(18046)
}
Why TypeScript does this
throw in JavaScript accepts any value:
throw new Error("normal");
throw "a string";
throw { code: 42 };
throw undefined;
Libraries do all of these. A rejected promise can carry anything too. So the honest type of a caught value is "I don't know", which is unknown.
For years TypeScript typed catch variables as any, which let error.message compile even when error was a string and error.message was undefined at runtime. TypeScript 4.0 let you opt in with catch (error: unknown), and TypeScript 4.4 added the useUnknownInCatchVariables option. According to the TSConfig reference, it defaults to true when strict is on.
That explains why the error often shows up suddenly:
- You turned on
"strict": true. - You upgraded to TypeScript 6.0 or later. The TypeScript 6.0 announcement says "
strictis nowtrueby default", so atsconfig.jsonthat never mentionedstrictnow gets it, and TypeScript 7 keeps that default. (TypeScript 7 is out.) - A project template or AI tool generated a strict config.
The basic fix: narrow with instanceof Error
Inside the if, TypeScript knows the value is an Error:
try {
JSON.parse(input);
} catch (error) {
if (error instanceof Error) {
console.error("Parse failed:", error.message);
} else {
console.error("Parse failed with a non-Error value:", error);
}
}
This handles the common case and is honest about the rare one. It also works with your own error subclasses:
class HttpError extends Error {
constructor(public status: number, message: string, options?: ErrorOptions) {
super(message, options);
this.name = "HttpError";
}
}
try {
await saveOrder(order);
} catch (err) {
if (err instanceof HttpError && err.status === 409) {
return showConflictMessage();
}
throw err; // not ours to handle, let it bubble up
}
One caveat: instanceof checks the prototype chain, so it can fail for errors created in another realm (an iframe, a vm context, some test runners' sandboxes). If that bites you, fall back to a structural check like the one below.
Type guards for errors that aren't Error
Some code throws plain objects. Node's system errors are Error instances with an extra code property, but you may also see { code, message } objects from SDKs. Write a type guard for the shape you expect:
function hasCode(value: unknown): value is { code: string } {
return (
typeof value === "object" &&
value !== null &&
"code" in value &&
typeof value.code === "string"
);
}
try {
await fs.readFile(path, "utf8");
} catch (err) {
if (hasCode(err) && err.code === "ENOENT") {
return null; // file missing is fine here
}
throw err;
}
The "code" in value check narrows value to an object with a code property (TypeScript 4.9 and later understand this), so typeof value.code compiles without a cast.
Keep type guards honest. A guard that returns true without really checking is a cast with extra steps.
If you validate data with a schema library such as Zod elsewhere in your app, the same idea applies here: describe the shape of the error you expect, parse the unknown value against it, and handle the failure case explicitly rather than assuming.
A small toError helper
When you just need an Error to log or rethrow, normalize once:
export function toError(value: unknown): Error {
if (value instanceof Error) return value;
if (typeof value === "string") return new Error(value);
try {
return new Error(JSON.stringify(value) ?? String(value));
} catch {
return new Error(String(value));
}
}
JSON.stringify returns undefined for values like undefined itself, hence the ??, and the try covers values it can't serialize, such as circular objects or BigInt. Then:
try {
await syncInventory();
} catch (err) {
const error = toError(err);
logger.error({ err: error }, error.message);
}
Use it at the edges where you log or report. In the middle of your code, prefer narrowing for the specific errors you can actually handle and rethrowing the rest.
Keep the original with Error.cause
When you catch an error and throw a more useful one, don't lose the original. ES2022 added a cause option to the Error constructor:
async function loadUser(id: string) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new HttpError(res.status, `GET /api/users/${id} failed`);
return await res.json();
} catch (err) {
throw new Error(`Could not load user ${id}`, { cause: err });
}
}
You can pass the unknown value straight in, because cause is itself typed as unknown. Whoever catches the outer error can inspect error.cause (and must narrow it the same way). Node prints the cause chain in uncaught error output, and many loggers and error trackers record it.
To get the types, your tsconfig.json needs "lib" or "target" of ES2022 or later. On older settings, new Error(msg, { cause }) is a type error even though modern runtimes support it.
Why not just use any?
You can write catch (error: any) and the error goes away. TypeScript allows an annotation of any or unknown on catch variables and nothing else (catch (e: Error) is error TS1196). You can also set "useUnknownInCatchVariables": false to get the old behaviour everywhere.
Both work, and both bring back the bug the flag exists to catch:
catch (error: any) {
showToast(error.message); // shows "undefined" when someone threw a string
if (error.response.status === 401) logout(); // crashes inside your error handler
}
An exception in the catch block is the worst place for a crash, because it replaces the error you were trying to handle. With unknown, the compiler makes you decide what to do with each shape.
Reasonable uses of any here: a quick script, or a migration where you flip the flag off temporarily and fix files one at a time. For new code, narrowing costs one if.
Promise .catch() callbacks
useUnknownInCatchVariables only affects try/catch. The reason in promise.catch((reason) => ...) is still typed any by the standard library typings, so the same bug can hide there. Treat it as unknown yourself:
fetchData().catch((reason: unknown) => {
const error = toError(reason);
report(error);
});
Some lint setups (for example typescript-eslint's use-unknown-in-catch-callback-variable rule) can enforce this.
Summary
'error' is of type 'unknown'comes fromuseUnknownInCatchVariables, enabled bystrict(default since TypeScript 6.0).- Narrow with
instanceof Erroror your own subclasses; rethrow what you can't handle. - Write type guards for non-
Errorshapes like{ code }. - Use a
toErrorhelper at logging boundaries. - Wrap with
new Error(msg, { cause: err })to keep the original. - Avoid
any: it hides the cases that crash your error handling.
More on the type system in What Is TypeScript?, TypeScript generics and TypeScript for AI-generated code. For what happens to errors once they leave your code, see error monitoring for beginners.
EasySpawn runs Claude Code on a persistent server where it can run tsc --noEmit against your real project after every change. See how it works or join the waitlist.
Related: TypeScript 7 Is Out: The Go-Native Compiler and What It Means for Your Project · What Is TypeScript? JavaScript With Labels, Explained for Beginners · TypeScript Generics Explained (Without the Headache) · Why TypeScript Makes AI-Generated Code Safer
Keep reading
Structured Logging: Logs You Can Actually Search
console.log('user saved') is useless at 3am when you need every request user 4812 made in the last hour. How structured logs work, what fields to include, request IDs that tie a request together, log levels that mean something, what never to log, and how logs make AI agents better debuggers.
CPU Steal Time Explained: Why Your VPS Is Slow When Nothing's Running
Steal time (%st in top) is time your virtual machine wanted the CPU but the hypervisor gave it to someone else. How to measure it with top, vmstat and mpstat, what levels are normal, how it differs from high load, why shared vCPUs suffer from it, and what to do when it's hurting your app.