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

feat(eslint-plugin): [no-magic-numbers] ignoreTypeIndexes option #4789

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
24 changes: 24 additions & 0 deletions packages/eslint-plugin/docs/rules/no-magic-numbers.md
Expand Up @@ -36,13 +36,15 @@ interface Options extends BaseNoMagicNumbersOptions {
ignoreEnums?: boolean;
ignoreNumericLiteralTypes?: boolean;
ignoreReadonlyClassProperties?: boolean;
ignoreTypeIndexes?: boolean;
}

const defaultOptions: Options = {
...baseNoMagicNumbersDefaultOptions,
ignoreEnums: false,
ignoreNumericLiteralTypes: false,
ignoreReadonlyClassProperties: false,
ignoreTypeIndexes: false,
};
```

Expand Down Expand Up @@ -118,6 +120,28 @@ class Foo {
}
```

### `ignoreTypeIndexes`

A boolean to specify if numbers used to index types are okay. `false` by default.

Examples of **incorrect** code for the `{ "ignoreTypeIndexes": false }` option:

```ts
/*eslint @typescript-eslint/no-magic-numbers: ["error", { "ignoreTypeIndexes": false }]*/

type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
```

Examples of **correct** code for the `{ "ignoreTypeIndexes": true }` option:

```ts
/*eslint @typescript-eslint/no-magic-numbers: ["error", { "ignoreTypeIndexes": true }]*/

type Foo = Bar[0];
type Baz = Parameters<Foo>[2];
```

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Heh, it's a pity this docs page doesn't use the newer tabbed format others do. No need to change in this PR though; I'm going to try to make docs a bit more automated soon.

<sup>

Taken with ❤️ [from ESLint core](https://github.com/eslint/eslint/blob/main/docs/rules/no-magic-numbers.md)
Expand Down
30 changes: 30 additions & 0 deletions packages/eslint-plugin/src/rules/no-magic-numbers.ts
Expand Up @@ -24,6 +24,9 @@ const schema = util.deepMerge(
ignoreReadonlyClassProperties: {
type: 'boolean',
},
ignoreTypeIndexes: {
type: 'boolean',
},
},
},
);
Expand Down Expand Up @@ -70,6 +73,15 @@ export default util.createRule<Options, MessageIds>({
return;
}

// Check if the node is a type index
if (
options.ignoreTypeIndexes &&
(typeof node.value === 'number' || typeof node.value === 'bigint') &&
isAncestorTSIndexedAccessType(node)
) {
return;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW, this looks good to me.
The only difference with my implementation is that I reported invalid nodes in this statement, similar to "Check if the node is a readonly class property". This way, we can return early which should be faster?

Also, good catch for the union types - this was something that I overlooked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timdeschryver Thanks! I refactored things a little in d1e65be so if any of the four ignorable TypeScript rules are triggered it will report early. Is that better?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yea, this should work.
If we go into more details I would remove the else if (isAllowed === false) statement to remove the indentation, and perhaps move the isAllowed logic into its own method.

Keep in mind that I'm not a member of typescript-eslint 😅

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timdeschryver Realized I never responded to this, sorry - and thank you for the feedback.

remove the else if (isAllowed === false) statement

I don’t think I can remove the isAllowed === false case because it’s possible for isAllowed to be undefined, so I intend to explicitly check if it is true or false in that if/else if block. If it is neither it will fall back to the base rule.

Perhaps I should move the final rules.Literal(node); line of the function into an else block to make that more explicit?

move the isAllowed logic into its own method

Looking at a few other rule definitions at random it does seem like they keep the core rule logic in the create function, which makes sense to me. I’m not sure moving isAllowed into its own function would improve readability, and feels like it would simply cause people to have to jump to look elsewhere for what is essentially the meat of the rule.

Feel free to push back if you (or @JoshuaKGoldberg?) disagree though, and I will happily take another look.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No problem @davecardwell !
Thanks for the elaboration, that does make sense.

}

// Check if the node is a readonly class property
if (
(typeof node.value === 'number' || typeof node.value === 'bigint') &&
Expand Down Expand Up @@ -216,3 +228,21 @@ function isParentTSReadonlyPropertyDefinition(node: TSESTree.Literal): boolean {

return false;
}

/**
* Checks if the node is part of a type indexed access (eg. Foo[4])
* @param node the node to be validated.
* @returns true if the node is part of an indexed access
* @private
*/
function isAncestorTSIndexedAccessType(node: TSESTree.Literal): boolean {
// Handle unary expressions (eg. -4)
let ancestor = getLiteralParent(node);

// Go up another level if we’re part of a type union (eg. 1 | 2)
if (ancestor?.parent?.type === AST_NODE_TYPES.TSUnionType) {
ancestor = ancestor.parent;
}

return ancestor?.parent?.type === AST_NODE_TYPES.TSIndexedAccessType;
}
142 changes: 142 additions & 0 deletions packages/eslint-plugin/tests/rules/no-magic-numbers.test.ts
Expand Up @@ -58,6 +58,42 @@ class Foo {
`,
options: [{ ignoreReadonlyClassProperties: true }],
},
{
code: 'type Foo = Bar[0];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Bar[-1];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Bar[0xab];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Bar[5.6e1];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Bar[10n];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Bar[1 | -2];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: 'type Foo = Parameters<Bar>[2];',
options: [{ ignoreTypeIndexes: true }],
},
{
code: "type Foo = Bar['baz'];",
options: [{ ignoreTypeIndexes: true }],
},
{
code: "type Foo = Bar['baz'];",
options: [{ ignoreTypeIndexes: false }],
},
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few edge cases we'll also want to test for:

type Foo = Bar[1 & number];
type Other = {
    [0]: 3;
}

type Foo = {
  [K in keyof Other]: `${K & number}`;
};
type Foo = {
  [K in 0 | 1 | 2]: 0;
};
type Others = [ ['a'], ['b'] ];

type Foo = {
  [K in keyof Others[0]]: Others[K];
};

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JoshuaKGoldberg couple of quick questions on those:

type Foo = Bar[1 & number];

Sure, I check for union types so intersection should be covered too! Thanks.

type Other = {
    [0]: 3;
}

type Foo = {
  [K in keyof Other]: `${K & number}`;
};

Since the 0 is a TSPropertySignature, not a TSIndexedAccessType, would you still want it to be covered by this new ignoreTypeIndexes config? Seems like that should be a separate config?

Also, the 3 there should be an error, right? So perhaps string or some other non-numeric literal would be more appropriate for this test case?

type Foo = {
  [K in 0 | 1 | 2]: 0;
};

As above, TSPropertySignature.

type Others = [ ['a'], ['b'] ];

type Foo = {
  [K in keyof Others[0]]: Others[K];
};

I’ll add a test to ensure the Others[0] part is covered.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great questions!

check for union types so intersection should be covered too

Bar[1 & number] is a bit different syntax from ${K & number}. I think it'd be good to have an explicit test for both. The code right now might not differentiate, but it's ripe for future refactors to miss it.

Since the 0 is a TSPropertySignature, not a TSIndexedAccessType, would you still want it to be covered by this new ignoreTypeIndexes config?

I'm not requesting changes to logic, just that it be covered. Agreed that they're different things -- the tests should validate that ignoreTypeIndexes doesn't remove the complaint on it.

Also, the 3 there should be an error, right?

Yes. That's already covered though; I'm really more interested in the TSPropertySignature.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JoshuaKGoldberg Thank you for clarifying. In af1ddb7 I added support for intersection types, nesting of union/intersection types, and the additional invalid test cases you suggested.

],

invalid: [
Expand Down Expand Up @@ -268,5 +304,111 @@ class Foo {
},
],
},
{
code: 'type Foo = Bar[0];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '0',
},
line: 1,
column: 16,
},
],
},
{
code: 'type Foo = Bar[-1];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '-1',
},
line: 1,
column: 16,
},
],
},
{
code: 'type Foo = Bar[0xab];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '0xab',
},
line: 1,
column: 16,
},
],
},
{
code: 'type Foo = Bar[5.6e1];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '5.6e1',
},
line: 1,
column: 16,
},
],
},
{
code: 'type Foo = Bar[10n];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '10n',
},
line: 1,
column: 16,
},
],
},
{
code: 'type Foo = Bar[1 | -2];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '1',
},
line: 1,
column: 16,
},
{
messageId: 'noMagic',
data: {
raw: '-2',
},
line: 1,
column: 20,
},
],
},
{
code: 'type Foo = Parameters<Bar>[2];',
options: [{ ignoreTypeIndexes: false }],
errors: [
{
messageId: 'noMagic',
data: {
raw: '2',
},
line: 1,
column: 28,
},
],
},
],
});
1 change: 1 addition & 0 deletions packages/eslint-plugin/typings/eslint-rules.d.ts
Expand Up @@ -319,6 +319,7 @@ declare module 'eslint/lib/rules/no-magic-numbers' {
ignoreNumericLiteralTypes?: boolean;
ignoreEnums?: boolean;
ignoreReadonlyClassProperties?: boolean;
ignoreTypeIndexes?: boolean;
},
],
{
Expand Down