Skip to content

Commit

Permalink
fix(eslint-plugin): [consistent-indexed-object-style] do not autofix …
Browse files Browse the repository at this point in the history
…if interface has extends (#3009)
  • Loading branch information
armano2 authored Feb 28, 2021
1 parent 25f459c commit b0475af
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createRule } from '../util';
import {
AST_NODE_TYPES,
TSESTree,
TSESLint,
} from '@typescript-eslint/experimental-utils';

type MessageIds = 'preferRecord' | 'preferIndexSignature';
Expand Down Expand Up @@ -66,6 +67,7 @@ export default createRule<Options, MessageIds>({
node: TSESTree.Node,
prefix: string,
postfix: string,
safeFix = true,
): void {
if (members.length !== 1) {
return;
Expand Down Expand Up @@ -98,14 +100,16 @@ export default createRule<Options, MessageIds>({
context.report({
node,
messageId: 'preferRecord',
fix(fixer) {
const key = sourceCode.getText(keyType.typeAnnotation);
const value = sourceCode.getText(valueType.typeAnnotation);
const record = member.readonly
? `Readonly<Record<${key}, ${value}>>`
: `Record<${key}, ${value}>`;
return fixer.replaceText(node, `${prefix}${record}${postfix}`);
},
fix: safeFix
? (fixer): TSESLint.RuleFix => {
const key = sourceCode.getText(keyType.typeAnnotation);
const value = sourceCode.getText(valueType.typeAnnotation);
const record = member.readonly
? `Readonly<Record<${key}, ${value}>>`
: `Record<${key}, ${value}>`;
return fixer.replaceText(node, `${prefix}${record}${postfix}`);
}
: null,
});
}

Expand All @@ -128,6 +132,7 @@ export default createRule<Options, MessageIds>({
node,
`type ${node.id.name}${genericTypes} = `,
';',
!node.extends?.length,
);
},
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ interface Foo {
[];
}
`,

// 'index-signature'
// Unhandled type
{
Expand Down Expand Up @@ -166,6 +165,20 @@ type Foo<A> = Record<string, A>;
errors: [{ messageId: 'preferRecord', line: 2, column: 1 }],
},

// Interface with extends
{
code: `
interface B extends A {
[index: number]: unknown;
}
`,
output: `
interface B extends A {
[index: number]: unknown;
}
`,
errors: [{ messageId: 'preferRecord', line: 2, column: 1 }],
},
// Readonly interface with generic parameter
{
code: `
Expand Down

0 comments on commit b0475af

Please # to comment.