1 | # `no-implicit-any-catch`
|
2 |
|
3 | Disallow usage of the implicit `any` type in catch clauses.
|
4 |
|
5 | TypeScript 4.0 added support for adding an explicit `any` or `unknown` type annotation on a catch clause variable.
|
6 |
|
7 | By default, TypeScript will type a catch clause variable as `any`, so explicitly annotating it as `unknown` can add a lot of safety to your codebase.
|
8 |
|
9 | The `noImplicitAny` flag in TypeScript does not cover this for backwards compatibility reasons, however you can use `useUnknownInCatchVariables` (part of `strict`) instead of this rule.
|
10 |
|
11 | ## DEPRECATED
|
12 |
|
13 | ## Rule Details
|
14 |
|
15 | This rule requires an explicit type to be declared on a catch clause variable.
|
16 |
|
17 | Examples of code for this rule:
|
18 |
|
19 |
|
20 |
|
21 | ### ❌ Incorrect
|
22 |
|
23 | ```ts
|
24 | try {
|
25 | // ...
|
26 | } catch (e) {
|
27 | // ...
|
28 | }
|
29 | ```
|
30 |
|
31 | ### ✅ Correct
|
32 |
|
33 |
|
34 |
|
35 |
|
36 | ```ts
|
37 | try {
|
38 | // ...
|
39 | } catch (e: unknown) {
|
40 | // ...
|
41 | }
|
42 | ```
|
43 |
|
44 |
|
45 |
|
46 | ## Options
|
47 |
|
48 | The rule accepts an options object with the following properties:
|
49 |
|
50 | ```ts
|
51 | type Options = {
|
52 | // if false, disallow specifying `: any` as the error type as well. See also `no-explicit-any`
|
53 | allowExplicitAny: boolean;
|
54 | };
|
55 |
|
56 | const defaults = {
|
57 | allowExplicitAny: false,
|
58 | };
|
59 | ```
|
60 |
|
61 | ### `allowExplicitAny`
|
62 |
|
63 | The follow is is **_not_** considered a warning with `{ allowExplicitAny: true }`
|
64 |
|
65 |
|
66 |
|
67 |
|
68 | ```ts
|
69 | try {
|
70 | // ...
|
71 | } catch (e: any) {
|
72 | // ...
|
73 | }
|
74 | ```
|
75 |
|
76 |
|
77 |
|
78 | ## When Not To Use It
|
79 |
|
80 | If you are not using TypeScript 4.0 (or greater), then you will not be able to use this rule, annotations on catch clauses is not supported.
|
81 |
|
82 | ## Further Reading
|
83 |
|
84 | - [TypeScript 4.0 Release Notes](https://devblogs.microsoft.com/typescript/announcing-typescript-4-0/#unknown-on-catch)
|
85 |
|
86 | ## Attributes
|
87 |
|
88 | - Configs:
|
89 | - [ ] ✅ Recommended
|
90 | - [ ] 🔒 Strict
|
91 | - [x] 🔧 Fixable
|
92 | - [ ] 💭 Requires type information
|