forked from typescript-eslint/typescript-eslint
/
prefer-ts-expect-error.ts
76 lines (70 loc) · 2.21 KB
/
prefer-ts-expect-error.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
import * as util from '../util';
import {
AST_TOKEN_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';
import {
RuleFixer,
RuleFix,
} from '@typescript-eslint/experimental-utils/dist/ts-eslint';
type MessageIds = 'preferExpectErrorComment';
export default util.createRule<[], MessageIds>({
name: 'prefer-ts-expect-error',
meta: {
type: 'problem',
docs: {
description: 'Recommends using `@ts-expect-error` over `@ts-ignore`',
category: 'Best Practices',
recommended: false,
},
fixable: 'code',
messages: {
preferExpectErrorComment:
'Use "@ts-expect-error" to ensure an error is actually being suppressed.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const tsIgnoreRegExp = /(^|\n)((\*)*(\/)*\s*(\/\*)*\s*)*\s*@ts-ignore/;
const sourceCode = context.getSourceCode();
function getLastCommentLine(comment: TSESTree.Comment): string {
if (comment.type === AST_TOKEN_TYPES.Line) {
return comment.value;
}
// For multiline comments - we look at only the last line.
const commentlines = comment.value.split('/\n');
return commentlines[commentlines.length - 1];
}
return {
Program(): void {
const comments = sourceCode.getAllComments();
comments.forEach(comment => {
if (tsIgnoreRegExp.test(getLastCommentLine(comment))) {
const lineCommentRuleFixer = (fixer: RuleFixer): RuleFix =>
fixer.replaceText(
comment,
`//${comment.value.replace('@ts-ignore', '@ts-expect-error')}`,
);
const blockCommentRuleFixer = (fixer: RuleFixer): RuleFix =>
fixer.replaceText(
comment,
`/*${comment.value.replace(
'@ts-ignore',
'@ts-expect-error',
)}*/`,
);
context.report({
node: comment,
messageId: 'preferExpectErrorComment',
fix:
comment.type === AST_TOKEN_TYPES.Line
? lineCommentRuleFixer
: blockCommentRuleFixer,
});
}
});
},
};
},
});