forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-meaningless-void-operator.ts
95 lines (90 loc) · 2.62 KB
/
no-meaningless-void-operator.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 { ESLintUtils, TSESLint, TSESTree } from '@typescript-eslint/utils';
import * as tsutils from 'tsutils';
import * as util from '../util';
import * as ts from 'typescript';
type Options = [
{
checkNever: boolean;
},
];
export default util.createRule<
Options,
'meaninglessVoidOperator' | 'removeVoid'
>({
name: 'no-meaningless-void-operator',
meta: {
type: 'suggestion',
docs: {
description:
'Disallow the `void` operator except when used to discard a value',
recommended: 'strict',
requiresTypeChecking: true,
},
fixable: 'code',
hasSuggestions: true,
messages: {
meaninglessVoidOperator:
"void operator shouldn't be used on {{type}}; it should convey that a return value is being ignored",
removeVoid: "Remove 'void'",
},
schema: [
{
type: 'object',
properties: {
checkNever: {
type: 'boolean',
default: false,
},
},
additionalProperties: false,
},
],
},
defaultOptions: [{ checkNever: false }],
create(context, [{ checkNever }]) {
const parserServices = ESLintUtils.getParserServices(context);
const checker = parserServices.program.getTypeChecker();
const sourceCode = context.getSourceCode();
return {
'UnaryExpression[operator="void"]'(node: TSESTree.UnaryExpression): void {
const fix = (fixer: TSESLint.RuleFixer): TSESLint.RuleFix => {
return fixer.removeRange([
sourceCode.getTokens(node)[0].range[0],
sourceCode.getTokens(node)[1].range[0],
]);
};
const argTsNode = parserServices.esTreeNodeToTSNodeMap.get(
node.argument,
);
const argType = checker.getTypeAtLocation(argTsNode);
const unionParts = tsutils.unionTypeParts(argType);
if (
unionParts.every(
part => part.flags & (ts.TypeFlags.Void | ts.TypeFlags.Undefined),
)
) {
context.report({
node,
messageId: 'meaninglessVoidOperator',
data: { type: checker.typeToString(argType) },
fix,
});
} else if (
checkNever &&
unionParts.every(
part =>
part.flags &
(ts.TypeFlags.Void | ts.TypeFlags.Undefined | ts.TypeFlags.Never),
)
) {
context.report({
node,
messageId: 'meaninglessVoidOperator',
data: { type: checker.typeToString(argType) },
suggest: [{ messageId: 'removeVoid', fix }],
});
}
},
};
},
});