Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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:

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
MemberAuthor

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 😁

JoshuaKGoldberg reacted with laugh emojiJoshuaKGoldberg reacted with heart emoji

```ts
interfaceFoo {
interfaceIndexSignatureInterface {
[key: string]: unknown;
}

typeFoo = {
typeIndexSignatureType = {
[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"'
interfaceFoo {
interfaceIndexSignatureInterface {
[key: string]: unknown;
}

typeFoo = {
typeIndexSignatureType = {
[key: string]: unknown;
};

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

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

```ts option='"record"'
typeFoo = Record<string, unknown>;
typeRecordType = Record<string, unknown>;
```

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

```ts option='"index-signature"'
typeFoo = Record<string, unknown>;
typeRecordType = Record<string, unknown>;
```

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

```ts option='"index-signature"'
interfaceFoo {
interfaceIndexSignatureInterface {
[key: string]: unknown;
}

typeFoo = {
typeIndexSignatureType = {
[key: string]: unknown;
};

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

</TabItem>
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff 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 DownExpand 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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 deletionpackages/eslint-plugin/src/rules/typedef.ts
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,7 @@ const enum OptionKeys {
VariableDeclarationIgnoreFunction = 'variableDeclarationIgnoreFunction',
}

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

type MessageIds = 'expectedTypedef' | 'expectedTypedefNamed';

Expand Down
5 changes: 2 additions & 3 deletionspackages/eslint-plugin/src/util/types.ts
View file
Open in desktop
Original file line numberDiff line numberDiff 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 abouthow customized files appear on GitHub.

Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp