@typescript-eslint/use-unknown-in-catch-callback-variable

Require the parameter of a promise rejection callback to be typed unknown

has suggestionsneeds types

Also called typescript-eslint/use-unknown-in-catch-callback-variable, typescript/use-unknown-in-catch-callback-variable

A promise can reject with anything: an Error, a string, undefined. TypeScript still types the parameter of a .catch() callback as any, so error.message compiles, and then throws if the value is undefined. With : unknown, TypeScript makes you check what you got first.

The second argument of .then() is checked too. TypeScript's useUnknownInCatchVariables does the same for catch (error) clauses, but it doesn't reach these callbacks.

Configure#

Off by default. This rule needs types, so turning it on makes bun lint type check your code first.

bunfig.toml
[lint.rules]
"@typescript-eslint/use-unknown-in-catch-callback-variable" = "error"

Examples#

example.ts3 problems
declare function save(): Promise<void>;

save().catch(error => {
  console.error(error.message);
});
save().catch((error: Error) => {
  console.error(error.message);
});
save().then(
  () => console.log("saved"),
  ({ message }) => console.error(message),
);
example.tsNo problems
declare function save(): Promise<void>;

save().catch((error: unknown) => {
  console.error(error instanceof Error ? error.message : String(error));
});
save().catch(() => {
  console.error("could not save");
});