require-use-unknown-in-catch-variables
Require "useUnknownInCatchVariables": true in compilerOptions so that
catch-clause variables are typed as unknown rather than implicitly any.
Targeted pattern scopeโ
The compilerOptions.useUnknownInCatchVariables field in any tsconfig*.json
file.
What this rule reportsโ
This rule reports when compilerOptions.useUnknownInCatchVariables is absent
or explicitly set to false, unless compilerOptions.strict is already set to
true.
Why this rule existsโ
Before TypeScript 4.4, the implicit type of a catch-clause variable was
always any:
try {
doSomething();
} catch (error) {
// error: any โ you can call anything on it without TypeScript objecting
console.log(error.message); // no type error, but may be undefined
}
useUnknownInCatchVariables: true (introduced in TypeScript 4.4 and included
in strict: true since then) changes the type of error to unknown,
forcing you to narrow it before use:
try {
doSomething();
} catch (error) {
// error: unknown โ must narrow before use
if (error instanceof Error) {
console.log(error.message); // safe
}
}
This prevents accidental property access on values that may not be Error
instances at all โ for example, throw "string" or throw 42 are both valid
in JavaScript.
Note: useUnknownInCatchVariables is already implied when strict: true is
set. This rule is useful when you want to enforce the flag explicitly, or when
strict is not set.
The auto-fixer adds "useUnknownInCatchVariables": true to compilerOptions.
โ Incorrectโ
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": false
}
}
strict is disabled so useUnknownInCatchVariables is also disabled.
{
"compilerOptions": {
"useUnknownInCatchVariables": false
}
}
Explicitly opting out of unknown-typed catch variables.
โ Correctโ
{
"compilerOptions": {
"strict": true
}
}
strict: true implies useUnknownInCatchVariables: true.
{
"compilerOptions": {
"useUnknownInCatchVariables": true
}
}
Explicitly enabled.
When not to use itโ
Disable this rule in projects that intentionally throw non-Error values and
have existing catch clauses that rely on any typing. Migrating those clauses
to narrow against unknown is the correct long-term fix, but can be a large
one-time refactor.
Package documentationโ
Rule catalog ID: R030