UNPKG

2.85 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const utils_1 = require("@typescript-eslint/utils");
4const util_1 = require("../util");
5exports.default = (0, util_1.createRule)({
6 name: 'prefer-literal-enum-member',
7 meta: {
8 type: 'suggestion',
9 docs: {
10 description: 'Require that all enum members be literal values to prevent unintended enum member name shadow issues',
11 recommended: false,
12 requiresTypeChecking: false,
13 },
14 messages: {
15 notLiteral: `Explicit enum value must only be a literal value (string, number, boolean, etc).`,
16 },
17 schema: [
18 {
19 type: 'object',
20 properties: {
21 allowBitwiseExpressions: {
22 type: 'boolean',
23 },
24 },
25 additionalProperties: false,
26 },
27 ],
28 },
29 defaultOptions: [
30 {
31 allowBitwiseExpressions: false,
32 },
33 ],
34 create(context, [{ allowBitwiseExpressions }]) {
35 return {
36 TSEnumMember(node) {
37 // If there is no initializer, then this node is just the name of the member, so ignore.
38 if (node.initializer == null) {
39 return;
40 }
41 // any old literal
42 if (node.initializer.type === utils_1.AST_NODE_TYPES.Literal) {
43 return;
44 }
45 // TemplateLiteral without expressions
46 if (node.initializer.type === utils_1.AST_NODE_TYPES.TemplateLiteral &&
47 node.initializer.expressions.length === 0) {
48 return;
49 }
50 // -1 and +1
51 if (node.initializer.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
52 node.initializer.argument.type === utils_1.AST_NODE_TYPES.Literal &&
53 (['+', '-'].includes(node.initializer.operator) ||
54 (allowBitwiseExpressions && node.initializer.operator === '~'))) {
55 return;
56 }
57 if (allowBitwiseExpressions &&
58 node.initializer.type === utils_1.AST_NODE_TYPES.BinaryExpression &&
59 ['|', '&', '^', '<<', '>>', '>>>'].includes(node.initializer.operator) &&
60 node.initializer.left.type === utils_1.AST_NODE_TYPES.Literal &&
61 node.initializer.right.type === utils_1.AST_NODE_TYPES.Literal) {
62 return;
63 }
64 context.report({
65 node: node.id,
66 messageId: 'notLiteral',
67 });
68 },
69 };
70 },
71});
72//# sourceMappingURL=prefer-literal-enum-member.js.map
\No newline at end of file