Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท tsconfig: Type Checking Options

TypeScript useUnknownInCatchVariables option

Reference for useUnknownInCatchVariables: why the catch variable is unknown, error TS18046, narrowing with instanceof, and the catch (e: any) escape hatch.

Anything can be thrown in JavaScript: an Error, a string, a number, undefined. So the value in a catch clause could be of any type. useUnknownInCatchVariables tells TypeScript to give the catch variable the type unknown instead of any, which forces you to check what it is before using it.

The option is part of strict. With it off, catch (e) gives e the type any, and e.message compiles even when e is not an object at all.

TypeScript
try {
  riskyWork();
} catch (error) {
  // error: unknown
  if (error instanceof Error) console.log(error.message);
}

Try it

TypeScript Narrowing an unknown error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript The compiler error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

JSON
{ "compilerOptions": { "useUnknownInCatchVariables": true } }
Part Description
Value true or false. Default: false, but true when strict is enabled. Added in TypeScript 4.4.
Error TS18046: 'error' is of type 'unknown'. when you read a property on the catch variable without narrowing.
Opt out per clause catch (e: unknown) always works; catch (e: any) is allowed and restores the old behavior for that clause only.

Usage notes

  • Only any and unknown can annotate a catch variable. Other types such as Error are not allowed, because the compiler cannot prove what was thrown.
  • Narrow before use: instanceof Error, typeof x === "string", or a custom type guard. Libraries often throw subclasses, so instanceof against the specific class is common.
  • Write a helper such as toMessage(e: unknown): string once and reuse it, rather than repeating narrowing everywhere.
  • Promise rejections are not covered: .catch((e) => ...) callbacks get any from the Promise typings. Narrow them by hand.
  • finally has no variable, so nothing changes there.
  • Optional catch binding (catch { ... }) never had the issue; use it when you do not need the error value.
  • Error causes (new Error("x", { cause })) are typed unknown, so narrowing applies there too.