forked from typescript-eslint/typescript-eslint
/
no-implicit-any-catch.ts
95 lines (92 loc) · 2.34 KB
/
no-implicit-any-catch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import * as util from '../util';
import {
TSESLint,
AST_NODE_TYPES,
} from '@typescript-eslint/experimental-utils';
export type Options = [
{
allowExplicitAny: boolean;
},
];
export type MessageIds =
| 'implicitAnyInCatch'
| 'explicitAnyInCatch'
| 'suggestExplicitUnknown';
export default util.createRule<Options, MessageIds>({
name: 'no-implicit-any-catch',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow usage of the implicit `any` type in catch clauses',
category: 'Best Practices',
recommended: false,
suggestion: true,
},
fixable: 'code',
messages: {
implicitAnyInCatch: 'Implicit any in catch clause',
explicitAnyInCatch: 'Explicit any in catch clause',
suggestExplicitUnknown:
'Use `unknown` instead, this will force you to explicitly, and safely assert the type is correct.',
},
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
allowExplicitAny: {
type: 'boolean',
},
},
},
],
},
defaultOptions: [
{
allowExplicitAny: true,
},
],
create(context, [{ allowExplicitAny }]) {
return {
CatchClause(node): void {
if (!node.param) {
return; // ignore catch without variable
}
if (!node.param.typeAnnotation) {
context.report({
node,
messageId: 'implicitAnyInCatch',
suggest: [
{
messageId: 'suggestExplicitUnknown',
fix(fixer): TSESLint.RuleFix {
return fixer.insertTextAfter(node.param!, ': unknown');
},
},
],
});
} else if (
!allowExplicitAny &&
node.param.typeAnnotation.typeAnnotation.type ===
AST_NODE_TYPES.TSAnyKeyword
) {
context.report({
node,
messageId: 'explicitAnyInCatch',
suggest: [
{
messageId: 'suggestExplicitUnknown',
fix(fixer): TSESLint.RuleFix {
return fixer.replaceText(
node.param!.typeAnnotation!,
': unknown',
);
},
},
],
});
}
},
};
},
});