TS1196
Catch clause variable type annotation must be 'any' or 'unknown' if specified.
Broken Code ❌
type MyError = {
code: number;
};
try {
// ...
} catch (error: MyError) {
console.log(error.code);
}Fixed Code ✔️
Errors in catch clauses can only be typed with any or unknown. If you need a more precise error typing, you can use a type guard as follows:
// Type Guard
function isMyError(error: any): error is MyError {
return typeof error.code === 'number';
}
type MyError = {
code: number;
};
try {
// ...
} catch (error: unknown) {
if (isMyError(error)) {
console.log(error.code);
}
}