Skip to content

fix(eslint-plugin): [consistent-indexed-object-style] do not autofix if interface has extends #3009

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

Merged
merged 2 commits into from
Feb 28, 2021
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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