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
Reported:
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),
);
Not reported:
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");
});