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): [no-magic-numbers] add support for enums #543

Merged
merged 3 commits into from Jun 16, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
19 changes: 18 additions & 1 deletion packages/eslint-plugin/src/rules/no-magic-numbers.ts
Expand Up @@ -55,6 +55,18 @@ export default util.createRule<Options, MessageIds>({
return typeof node.value === 'number';
}

/**
* Checks if the node grandparent is a Typescript enum declaration
* @param node the node to be validated.
* @returns true if the node grandparent is a Typescript enum declaration
* @private
*/
function isGrandparentTSEnumDeclaration(node: TSESTree.Node): boolean {
jonathanrdelgado marked this conversation as resolved.
Show resolved Hide resolved
return node.parent && node.parent.parent
? node.parent.parent.type === AST_NODE_TYPES.TSEnumDeclaration
jonathanrdelgado marked this conversation as resolved.
Show resolved Hide resolved
: false;
}

/**
* Checks if the node grandparent is a Typescript type alias declaration
* @param node the node to be validated.
Expand Down Expand Up @@ -133,7 +145,12 @@ export default util.createRule<Options, MessageIds>({

return {
Literal(node) {
// Check TypeScript specific nodes
// Check if the node is a TypeScript enum declaration
if (isGrandparentTSEnumDeclaration(node)) {
return;
}

// Check TypeScript specific nodes for Numeric Literal
if (
options.ignoreNumericLiteralTypes &&
isNumber(node) &&
Expand Down
3 changes: 3 additions & 0 deletions packages/eslint-plugin/tests/rules/no-magic-numbers.test.ts
Expand Up @@ -17,6 +17,9 @@ ruleTester.run('no-magic-numbers', rule, {
{
code: 'type Foo = true;',
},
{
code: 'enum foo { SECOND = 1000 }',
},
{
code: 'type Foo = 1;',
options: [{ ignoreNumericLiteralTypes: true }],
Expand Down