Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(eslint-plugin): [prefer-literal-enum-member] allow negative numbe…
…rs (#2277)
  • Loading branch information
bradzacher committed Jul 6, 2020
1 parent ced6591 commit 00ac9c3
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 7 deletions.
25 changes: 18 additions & 7 deletions packages/eslint-plugin/src/rules/prefer-literal-enum-member.ts
@@ -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
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

0 comments on commit 00ac9c3

Please sign in to comment.