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.
try { riskyWork(); } catch (error) { // error: unknown if (error instanceof Error) console.log(error.message); }
Try it
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.
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
{ "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
anyandunknowncan annotate a catch variable. Other types such asErrorare 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, soinstanceofagainst the specific class is common. - Write a helper such as
toMessage(e: unknown): stringonce and reuse it, rather than repeating narrowing everywhere. - Promise rejections are not covered:
.catch((e) => ...)callbacks getanyfrom thePromisetypings. Narrow them by hand. finallyhas 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 typedunknown, so narrowing applies there too.
Related
strict,unknown,noImplicitAny- Lessons: Error handling, any, unknown and never