/
prefer-literal-enum-member.ts
55 lines (53 loc) · 1.55 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
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: [],
},
defaultOptions: [],
create(context) {
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 &&
['+', '-'].includes(node.initializer.operator) &&
node.initializer.argument.type === AST_NODE_TYPES.Literal
) {
return;
}
context.report({
node: node.id,
messageId: 'notLiteral',
});
},
};
},
});