Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(eslint-plugin): [prefer-literal-enum-member] allow negative numbers #2277

Merged
merged 1 commit into from Jul 6, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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