TS1196
error TS1196: Catch clause variable type annotation must be ‘any’ or ‘unknown’ if specified.
Broken Code ❌
1 2 3 4 5 6 7 8 9
| 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 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); } }
|
Video Tutorial