Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions packages/eslint-plugin/src/rules/prefer-literal-enum-member.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { AST_NODE_TYPES } from '@typescript-eslint/experimental-utils';
import { createRule } from '../util';

export default createRule<[], 'notLiteral'>({
export default createRule({
name: 'prefer-literal-enum-member',
meta: {
type: 'suggestion',
Expand All @@ -22,15 +22,26 @@ export default createRule<[], 'notLiteral'>({
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;
}
// -1 and +1
if (
node.initializer != null &&
node.initializer.type !== AST_NODE_TYPES.Literal
node.initializer.type === AST_NODE_TYPES.UnaryExpression &&
['+', '-'].includes(node.initializer.operator) &&
node.initializer.argument.type === AST_NODE_TYPES.Literal
) {
context.report({
node: node.id,
messageId: 'notLiteral',
});
return;
}

context.report({
node: node.id,
messageId: 'notLiteral',
});
},
};
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ enum ValidNumber {
}
`,
`
enum ValidNumber {
A = -42,
}
`,
`
enum ValidNumber {
A = +42,
}
`,
`
enum ValidNull {
A = null,
}
Expand Down Expand Up @@ -121,6 +131,44 @@ enum InvalidExpression {
},
{
code: `
enum InvalidExpression {
A = delete 2,
B = -a,
C = void 2,
D = ~2,
E = !0,
}
`,
errors: [
{
messageId: 'notLiteral',
line: 3,
column: 3,
},
{
messageId: 'notLiteral',
line: 4,
column: 3,
},
{
messageId: 'notLiteral',
line: 5,
column: 3,
},
{
messageId: 'notLiteral',
line: 6,
column: 3,
},
{
messageId: 'notLiteral',
line: 7,
column: 3,
},
],
},
{
code: `
const variable = 'Test';
enum InvalidVariable {
A = 'TestStr',
Expand Down