Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readTypeScript
#typescript#ts18046#catch-variables#type-narrowing
Bold white headline reading TS18046 beside a cyan error crate wrapped in an amber unknown veil.

Introduction & Quick Summary

A TypeScript build that used to pass suddenly fails with a single line in a catch block:

code
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:

ts
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:

ts
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.

ts
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 approachRuntime checkKeeps safetyWorks for cross-realm errorsTypical cost
e instanceof Erroryesyesnoone line
typeof e === "string"yesyesyesone branch
custom type guardyesyesyeshelper function
e as Errornonoclaims yeszero
catch (e: any)nonoclaims yeszero
useUnknownInCatchVariables: falsenono, project-wideclaims yesconfig change
String(e) or JSON.stringify(e)yespartialyesloses stack
ConfigurationCatch variable typeReading .messageRecommended for
strict: falseanyallowedlegacy code only
strict: trueunknownblockednew projects
strict: true plus useUnknownInCatchVariables: falseanyallowedstaged migration
strict: true plus explicit catch (e: unknown)unknownblockedexplicit intent
strict: true plus explicit catch (e: any)anyallowedrare interop
Where the thrown value comes fromStatic type at the catchUsual runtime shape
throw new Error(...) in your codeunknownError
JSON.parse failureunknownSyntaxError
fetch with a custom clientunknownError or plain object
third-party libraryunknownoften a plain object
Promise.reject("boom")unknown in try/catchstring

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:

ts
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:

ts
import vm from "node:vm" const foreign = vm.runInNewContext("new Error('from another realm')") foreign instanceof Error // false typeof foreign.message === "string" // true

Errors 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:

ts
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:

ts
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:

ts
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:

ts
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:

ts
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 only any and unknown are allowed as catch annotations. Use a guard instead.
  • e as Error silences the error and nothing else. If a string was thrown, .message is undefined at runtime and you log undefined while the stack trace is already lost.
  • typeof e === "object" is not enough. null satisfies it, and e.message still throws. Always add e !== null and check for the property.
  • Assuming .catch() is protected. Callback parameters default to any, so the compiler stays quiet; annotate them unknown to get TS18046 in the places that deserve it.
  • Turning the flag off project-wide. useUnknownInCatchVariables: false is a migration tool; leaving it off means every new catch block starts unsafe.
  • Version notes. useUnknownInCatchVariables arrived in TypeScript 4.4 and became part of strict; 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 documentation

The TypeScript documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.