Skip to content

feat(eslint-plugin): [consistent-indexed-object-style] report mapped types #10160

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
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 @@ -9,18 +9,24 @@ import TabItem from '@theme/TabItem';
>
> See **https://typescript-eslint.io/rules/consistent-indexed-object-style** for documentation.

TypeScript supports defining arbitrary object keys using an index signature. TypeScript also has a builtin type named `Record` to create an empty object defining only an index signature. For example, the following types are equal:
TypeScript supports defining arbitrary object keys using an index signature or mapped type.
TypeScript also has a builtin type named `Record` to create an empty object defining only an index signature.
For example, the following types are equal:
Copy link
Member

Choose a reason for hiding this comment

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

[Praise] 😄 I like the .\n splitting

Copy link
Member Author

Choose a reason for hiding this comment

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

Did it just for you 😁


```ts
interface Foo {
interface IndexSignatureInterface {
[key: string]: unknown;
}

type Foo = {
type IndexSignatureType = {
[key: string]: unknown;
};

type Foo = Record<string, unknown>;
type MappedType = {
[key in string]: unknown;
};

type RecordType = Record<string, unknown>;
```

Using one declaration form consistently improves code readability.
Expand All @@ -38,20 +44,24 @@ Using one declaration form consistently improves code readability.
<TabItem value="❌ Incorrect">

```ts option='"record"'
interface Foo {
interface IndexSignatureInterface {
[key: string]: unknown;
}

type Foo = {
type IndexSignatureType = {
[key: string]: unknown;
};

type MappedType = {
[key in string]: unknown;
};
```

</TabItem>
<TabItem value="✅ Correct">

```ts option='"record"'
type Foo = Record<string, unknown>;
type RecordType = Record<string, unknown>;
```

</TabItem>
Expand All @@ -63,20 +73,24 @@ type Foo = Record<string, unknown>;
<TabItem value="❌ Incorrect">

```ts option='"index-signature"'
type Foo = Record<string, unknown>;
type RecordType = Record<string, unknown>;
```

</TabItem>
<TabItem value="✅ Correct">

```ts option='"index-signature"'
interface Foo {
interface IndexSignatureInterface {
[key: string]: unknown;
}

type Foo = {
type IndexSignatureType = {
[key: string]: unknown;
};

type MappedType = {
[key in string]: unknown;
};
```

</TabItem>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
import type { ReportFixFunction } from '@typescript-eslint/utils/ts-eslint';

import { AST_NODE_TYPES, ASTUtils } from '@typescript-eslint/utils';

import { createRule } from '../util';
import { createRule, isParenthesized, nullThrows } from '../util';

type MessageIds = 'preferIndexSignature' | 'preferRecord';
type Options = ['index-signature' | 'record'];
Expand Down Expand Up @@ -142,6 +143,69 @@ export default createRule<Options, MessageIds>({
!node.extends.length,
);
},
TSMappedType(node): void {
const key = node.key;
const scope = context.sourceCode.getScope(key);

const scopeManagerKey = nullThrows(
scope.variables.find(
value => value.name === key.name && value.isTypeVariable,
),
'key type parameter must be a defined type variable in its scope',
);

// If the key is used to compute the value, we can't convert to a Record.
if (
scopeManagerKey.references.some(
reference => reference.isTypeReference,
)
) {
return;
}

const constraint = node.constraint;

if (
constraint.type === AST_NODE_TYPES.TSTypeOperator &&
constraint.operator === 'keyof' &&
!isParenthesized(constraint, context.sourceCode)
) {
// This is a weird special case, since modifiers are preserved by
// the mapped type, but not by the Record type. So this type is not,
// in general, equivalent to a Record type.
return;
}

// There's no builtin Mutable<T> type, so we can't autofix it really.
const canFix = node.readonly !== '-';

context.report({
node,
messageId: 'preferRecord',
...(canFix && {
fix: (fixer): ReturnType<ReportFixFunction> => {
const keyType = context.sourceCode.getText(constraint);
const valueType = context.sourceCode.getText(
node.typeAnnotation,
);

let recordText = `Record<${keyType}, ${valueType}>`;

if (node.optional === '+' || node.optional === true) {
recordText = `Partial<${recordText}>`;
} else if (node.optional === '-') {
recordText = `Required<${recordText}>`;
}

if (node.readonly === '+' || node.readonly === true) {
recordText = `Readonly<${recordText}>`;
}

return fixer.replaceText(node, recordText);
},
}),
});
},
TSTypeLiteral(node): void {
const parent = findParentDeclaration(node);
checkMembers(node.members, node, parent?.id, '', '');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ const optionTesters = (
tester,
}));
type Options = [
{ [Type in (typeof optionTesters)[number]['option']]?: boolean } & {
{
allow?: TypeOrValueSpecifier[];
},
} & Partial<Record<(typeof optionTesters)[number]['option'], boolean>>,
];

type MessageId = 'invalidType';
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/rules/typedef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ const enum OptionKeys {
VariableDeclarationIgnoreFunction = 'variableDeclarationIgnoreFunction',
}

type Options = { [k in OptionKeys]?: boolean };
type Options = Partial<Record<OptionKeys, boolean>>;

type MessageIds = 'expectedTypedef' | 'expectedTypedefNamed';

Expand Down
5 changes: 2 additions & 3 deletions packages/eslint-plugin/src/util/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export type MakeRequired<Base, Key extends keyof Base> = {
[K in Key]-?: NonNullable<Base[Key]>;
} & Omit<Base, Key>;
export type MakeRequired<Base, Key extends keyof Base> = Omit<Base, Key> &
Required<Record<Key, NonNullable<Base[Key]>>>;

export type ValueOf<T> = T[keyof T];

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading