TypeScript TS18046: 'e' is of type 'unknown'
TS18046 comes from useUnknownInCatchVariables: a caught error is unknown, not any. Narrow it with instanceof or a type guard before reading message.

Introduction & Quick Summary
A TypeScript build that used to pass suddenly fails with a single line in a catch block:
src/api/client.ts:41:14 - error TS18046: 'e' is of type 'unknown'.
41 console.error(e.message)
~Quick answer: since TypeScript 4.4, the variable bound by a catch clause is typed unknown instead of any whenever useUnknownInCatchVariables is on, and that flag is part of strict. Anything thrown at runtime can be a string, a plain object or a rejected promise value, so the compiler refuses to let you read .message until you prove the value is an Error. Narrow it with instanceof, a small type guard or a shared helper:
try {
await saveOrder(order)
} catch (e) {
if (e instanceof Error) {
logger.error(e.message) // e is Error here
} else {
logger.error(String(e))
}
}That is the whole fix in most projects: one instanceof check per catch block, or a helper that does it once. The rest covers which patterns survive real workloads, where instanceof Error fails, and how promise rejections differ.
Core Mechanics, Signatures & Reproducible Setup
The rule lives in tsconfig.json. strict: true enables a bundle of flags, one of which is useUnknownInCatchVariables. You can keep strict mode and flip only that flag back if a legacy codebase cannot be changed yet:
{
"compilerOptions": {
"module": "NodeNext",
"strict": true,
"useUnknownInCatchVariables": true
}
}With that configuration, these two handlers behave differently:
try {
JSON.parse(input)
} catch (e) {
e.message // TS18046: 'e' is of type 'unknown'
if (e instanceof Error) e.message // OK, narrowed
}
// Explicit annotation is still allowed, but only to any or unknown
try {
JSON.parse(input)
} catch (e: any) {
e.message // compiles, and gives up all safety
}The annotation catch (e: Error) is not allowed: only any or unknown are accepted there (TS1196). TypeScript cannot model "whatever was thrown", so it uses the safest type.
Narrowing works on catch variables as on parameters typed unknown: typeof, instanceof, in and type predicates all refine it, and control flow follows if, return and throw.
function isErrorLike(value: unknown): value is { message: string; name?: string } {
return typeof value === "object" && value !== null && "message" in value &&
typeof (value as { message: unknown }).message === "string"
}
try {
await handler()
} catch (e) {
if (isErrorLike(e)) {
report(e.message)
}
}To confirm the flag is what triggers the error, compile one file with npx tsc --noEmit, then flip useUnknownInCatchVariables to false: the same file compiles.
Key Comparison Table
| Narrowing approach | Runtime check | Keeps safety | Works for cross-realm errors | Typical cost |
|---|---|---|---|---|
e instanceof Error | yes | yes | no | one line |
typeof e === "string" | yes | yes | yes | one branch |
| custom type guard | yes | yes | yes | helper function |
e as Error | no | no | claims yes | zero |
catch (e: any) | no | no | claims yes | zero |
useUnknownInCatchVariables: false | no | no, project-wide | claims yes | config change |
String(e) or JSON.stringify(e) | yes | partial | yes | loses stack |
| Configuration | Catch variable type | Reading .message | Recommended for |
|---|---|---|---|
strict: false | any | allowed | legacy code only |
strict: true | unknown | blocked | new projects |
strict: true plus useUnknownInCatchVariables: false | any | allowed | staged migration |
strict: true plus explicit catch (e: unknown) | unknown | blocked | explicit intent |
strict: true plus explicit catch (e: any) | any | allowed | rare interop |
| Where the thrown value comes from | Static type at the catch | Usual runtime shape |
|---|---|---|
throw new Error(...) in your code | unknown | Error |
JSON.parse failure | unknown | SyntaxError |
fetch with a custom client | unknown | Error or plain object |
| third-party library | unknown | often a plain object |
Promise.reject("boom") | unknown in try/catch | string |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. A helper that every catch block can reuse
The least repetitive fix is one function that turns unknown into an Error:
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))
} catch {
return new Error(String(value))
}
}
try {
await publishPost(id)
} catch (e) {
const err = toError(e)
logger.error({ message: err.message, stack: err.stack })
}The JSON.stringify path handles libraries that throw a response object, but it throws on circular structures itself, which is why the inner try is there. Format large payloads with the JSON formatter while debugging instead of printing megabytes into the log.
2. instanceof Error fails across realms and in some runtimes
instanceof compares constructor identity in the current realm. An error from a vm context or an iframe is not an instance of your realm's Error, though it has message and stack:
import vm from "node:vm"
const foreign = vm.runInNewContext("new Error('from another realm')")
foreign instanceof Error // false
typeof foreign.message === "string" // trueErrors from a different copy of a library behave the same way. Across such a boundary prefer structural checks over instanceof, and keep the guard in one place.
3. Non-Error throws are common in libraries and in tests
Nothing forces throw to receive an Error; wrappers often rethrow { status, body } and test helpers throw strings. A guard for both shapes keeps the branches honest:
type ApiFailure = { status: number; body: unknown }
function isApiFailure(value: unknown): value is ApiFailure {
return typeof value === "object" && value !== null &&
"status" in value && typeof (value as ApiFailure).status === "number"
}
try {
await client.send(payload)
} catch (e) {
if (isApiFailure(e) && e.status === 429) {
await sleep(backoff())
} else if (e instanceof Error) {
throw e
} else {
throw new Error(`unexpected failure: ${String(e)}`)
}
}The final else rethrows a normalised Error, so callers do not repeat the narrowing. When a library throws a string you have to interpret, test the pattern with the regex tester first.
4. Promise rejections are typed differently from try/catch
In try/catch, the binding is unknown. In a .catch() callback, the parameter has type any by default, so TS18046 does not appear and unsafe access sneaks in:
fetchOrders()
.then(render)
.catch((e) => {
console.error(e.message) // no error, and no check either
})Annotate the parameter explicitly to get the same protection as try/catch, or move to async/await:
fetchOrders()
.then(render)
.catch((e: unknown) => {
console.error(toError(e).message)
})Framework wrappers declaring onError: (error: any) => void have the same gap; treat those signatures as a hint and narrow inside.
5. AggregateError, DOMException and other subclasses
Subclasses inherit from Error, so instanceof Error narrows them, but their useful fields live on the subclass:
try {
await Promise.any(tasks)
} catch (e) {
if (e instanceof AggregateError) {
for (const inner of e.errors) console.error(toError(inner).message)
} else if (e instanceof DOMException && e.name === "AbortError") {
return // expected cancellation
} else {
throw e
}
}AbortError deserves its own branch in any code that uses AbortController: cancellation is not a failure, and logging it as one hides real problems.
6. Narrowing at the boundary instead of everywhere
A wrapper that turns every rejection into a typed result keeps unknown out of downstream code, and keeps the original value in cause for debugging:
type Result<T> = { ok: true; value: T } | { ok: false; error: Error; cause: unknown }
export async function attempt<T>(fn: () => Promise<T>): Promise<Result<T>> {
try {
return { ok: true, value: await fn() }
} catch (cause) {
return { ok: false, error: toError(cause), cause }
}
}Common Compilation/Runtime Mistakes & Version Gotchas
catch (e: Error)does not compile. TS1196 fires because onlyanyandunknownare allowed as catch annotations. Use a guard instead.e as Errorsilences the error and nothing else. If a string was thrown,.messageisundefinedat runtime and you logundefinedwhile the stack trace is already lost.typeof e === "object"is not enough.nullsatisfies it, ande.messagestill throws. Always adde !== nulland check for the property.- Assuming
.catch()is protected. Callback parameters default toany, so the compiler stays quiet; annotate themunknownto get TS18046 in the places that deserve it. - Turning the flag off project-wide.
useUnknownInCatchVariables: falseis a migration tool; leaving it off means every new catch block starts unsafe. - Version notes.
useUnknownInCatchVariablesarrived in TypeScript 4.4 and became part ofstrict; projects pinned below 4.4 never see TS18046, which is why it can "appear" after a dependency bumps the compiler.
Once the flags and the helper are in place, TS18046 stops being noise: every catch block either narrows the value or explicitly converts it, and the compiler enforces that at review time. Official documentation: the useUnknownInCatchVariables compiler option and the narrowing chapter explain the exact rules used above.
Official references
primary documentationThe TypeScript documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript TS2349: This expression is not callable
TS2349 means the value has no call signature at that point. Narrow unions, fix module default imports and guard optional calls instead of asserting.
TypeScript: Cannot find name 'process' with @types/node
TS2304 on process or Buffer means the compiler has no Node declarations. Install @types/node, stop excluding it, and align its version to the runtime.
TypeScript TS2339: Property does not exist on type
TS2339 means the declared type has no such member. Declare the shape, narrow unions and guard unknown values instead of casting at the read.
TypeScript TS2564: Property has no initializer and is not definitely assigned
TS2564 means the compiler can't prove a field is assigned before the constructor ends. Defaults, definite assignment and optional fields each fit one case.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.