/
prefer-literal-enum-member.ts
82 lines (79 loc) · 2.3 KB
/
prefer-literal-enum-member.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
import { AST_NODE_TYPES } from '@typescript-eslint/experimental-utils';
import { createRule } from '../util';
export default createRule({
name: 'prefer-literal-enum-member',
meta: {
type: 'suggestion',
docs: {
description:
'Require that all enum members be literal values to prevent unintended enum member name shadow issues',
category: 'Best Practices',
recommended: false,
requiresTypeChecking: false,
},
messages: {
notLiteral: `Explicit enum value must only be a literal value (string, number, boolean, etc).`,
},
schema: [
{
type: 'object',
properties: {
allowBitwiseExpressions: {
type: 'boolean',
},
},
additionalProperties: false,
},
],
},
defaultOptions: [
{
allowBitwiseExpressions: false,
},
],
create(context, [{ allowBitwiseExpressions }]) {
return {
TSEnumMember(node): void {
// If there is no initializer, then this node is just the name of the member, so ignore.
if (node.initializer == null) {
return;
}
// any old literal
if (node.initializer.type === AST_NODE_TYPES.Literal) {
return;
}
// TemplateLiteral without expressions
if (
node.initializer.type === AST_NODE_TYPES.TemplateLiteral &&
node.initializer.expressions.length === 0
) {
return;
}
// -1 and +1
if (
node.initializer.type === AST_NODE_TYPES.UnaryExpression &&
node.initializer.argument.type === AST_NODE_TYPES.Literal &&
(['+', '-'].includes(node.initializer.operator) ||
(allowBitwiseExpressions && node.initializer.operator === '~'))
) {
return;
}
if (
allowBitwiseExpressions &&
node.initializer.type === AST_NODE_TYPES.BinaryExpression &&
['|', '&', '^', '<<', '>>', '>>>'].includes(
node.initializer.operator,
) &&
node.initializer.left.type === AST_NODE_TYPES.Literal &&
node.initializer.right.type === AST_NODE_TYPES.Literal
) {
return;
}
context.report({
node: node.id,
messageId: 'notLiteral',
});
},
};
},
});