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): add consistent-indexed-object-style rule #2401

Merged
merged 11 commits into from Sep 28, 2020
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
1 change: 1 addition & 0 deletions packages/eslint-plugin/README.md
Expand Up @@ -157,6 +157,7 @@ Pro Tip: For larger codebases you may want to consider splitting our linting int
| [`@typescript-eslint/prefer-optional-chain`](./docs/rules/prefer-optional-chain.md) | Prefer using concise optional chain expressions instead of chained logical ands | | | |
| [`@typescript-eslint/prefer-readonly`](./docs/rules/prefer-readonly.md) | Requires that private members are marked as `readonly` if they're never modified outside of the constructor | | :wrench: | :thought_balloon: |
| [`@typescript-eslint/prefer-readonly-parameter-types`](./docs/rules/prefer-readonly-parameter-types.md) | Requires that function parameters are typed as readonly to prevent accidental mutation of inputs | | | :thought_balloon: |
| [`@typescript-eslint/prefer-record`](./docs/rules/prefer-record.md) | Enforce or disallow the use of the record type style | | |
| [`@typescript-eslint/prefer-reduce-type-parameter`](./docs/rules/prefer-reduce-type-parameter.md) | Prefer using type parameter when calling `Array#reduce` instead of casting | | :wrench: | :thought_balloon: |
| [`@typescript-eslint/prefer-regexp-exec`](./docs/rules/prefer-regexp-exec.md) | Enforce that `RegExp#exec` is used instead of `String#match` if no global flag is provided | :heavy_check_mark: | | :thought_balloon: |
| [`@typescript-eslint/prefer-string-starts-ends-with`](./docs/rules/prefer-string-starts-ends-with.md) | Enforce the use of `String#startsWith` and `String#endsWith` instead of other equivalent methods of checking substrings | | :wrench: | :thought_balloon: |
Expand Down
67 changes: 67 additions & 0 deletions packages/eslint-plugin/docs/rules/prefer-record.md
@@ -0,0 +1,67 @@
# Enforce or disallow the use of the record type (`prefer-record`)

TypeScript supports defining object show keys can be flexible 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:

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

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

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

## Options

- `"record"`: Set to `"always"` to only allow the `Record` type. Set to `"never"` to only allow index signatures. (Defaults to `"always"`)

For example:

```CJSON
{
"@typescript-eslint/consistent-type-definitions": ["error", "never"]
}
```

## Rule details

This rule enforces a consistent way to define records.

Examples of **incorrect** code with `always` option.

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

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

Examples of **correct** code with `always` option.

```ts
type Foo = Record<string, unknown>;
```

Examples of **incorrect** code with `never` option.

```ts
type Foo = Record<string, unknown>;
```

Examples of **correct** code with `never` option.

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

type Foo = {
[key: string]: unknown;
};
```
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -114,6 +114,7 @@ export = {
'@typescript-eslint/promise-function-async': 'error',
quotes: 'off',
'@typescript-eslint/quotes': 'error',
'@typescript-eslint/prefer-record': 'error',
'@typescript-eslint/require-array-sort-compare': 'error',
'require-await': 'off',
'@typescript-eslint/require-await': 'error',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -79,6 +79,7 @@ import preferNullishCoalescing from './prefer-nullish-coalescing';
import preferOptionalChain from './prefer-optional-chain';
import preferReadonly from './prefer-readonly';
import preferReadonlyParameterTypes from './prefer-readonly-parameter-types';
import preferRecord from './prefer-record';
import preferReduceTypeParameter from './prefer-reduce-type-parameter';
import preferRegexpExec from './prefer-regexp-exec';
import preferStringStartsEndsWith from './prefer-string-starts-ends-with';
Expand Down Expand Up @@ -180,6 +181,7 @@ export default {
'prefer-optional-chain': preferOptionalChain,
'prefer-readonly-parameter-types': preferReadonlyParameterTypes,
'prefer-readonly': preferReadonly,
'prefer-record': preferRecord,
'prefer-reduce-type-parameter': preferReduceTypeParameter,
'prefer-regexp-exec': preferRegexpExec,
'prefer-string-starts-ends-with': preferStringStartsEndsWith,
Expand Down
118 changes: 118 additions & 0 deletions packages/eslint-plugin/src/rules/prefer-record.ts
@@ -0,0 +1,118 @@
import { createRule } from '../util';
import {
AST_NODE_TYPES,
TSESTree,
} from '@typescript-eslint/experimental-utils';

export default createRule({
name: 'prefer-record',
bradzacher marked this conversation as resolved.
Show resolved Hide resolved
meta: {
type: 'suggestion',
docs: {
description: 'Enforce a consistent record style',
category: 'Stylistic Issues',
// too opinionated to be recommended
recommended: false,
},
messages: {
preferRecord: 'A record is preferred over an index signature',
preferIndexSignature: 'An index signature is preferred over a record.',
},
fixable: 'code',
schema: [
{
enum: ['always', 'never'],
},
],
},
defaultOptions: ['always'],
create(context) {
const sourceCode = context.getSourceCode();

if (context.options[0] === 'never') {
return {
TSTypeReference(node): void {
const typeName = node.typeName as TSESTree.Identifier;
if (typeName.name !== 'Record') {
return;
}

const { params } = node.typeParameters!;
if (params.length !== 2) {
return;
}

context.report({
node,
messageId: 'preferIndexSignature',
fix(fixer) {
const key = sourceCode.getText(params[0]);
const type = sourceCode.getText(params[1]);
return fixer.replaceTextRange(
node.range,
`{ [key: ${key}]: ${type} }`,
);
},
});
},
};
}

/**
* Convert an index signature node to record code as string.
*/
function toRecord(node: TSESTree.TSIndexSignature): string {
const parameter = node.parameters[0] as TSESTree.Identifier;
const key = sourceCode.getText(parameter.typeAnnotation?.typeAnnotation);
const value = sourceCode.getText(node.typeAnnotation?.typeAnnotation);
return `Record<${key}, ${value}>`;
}

return {
TSTypeLiteral(node): void {
if (node.members.length !== 1) {
return;
}

const [member] = node.members;

if (member.type !== AST_NODE_TYPES.TSIndexSignature) {
return;
}

context.report({
node,
messageId: 'preferRecord',
fix(fixer) {
return fixer.replaceTextRange(node.range, toRecord(member));
},
});
},

TSInterfaceDeclaration(node): void {
const { body } = node.body;

if (body.length !== 1) {
return;
}

const [index] = body;
if (index.type !== AST_NODE_TYPES.TSIndexSignature) {
return;
}

context.report({
node,
messageId: 'preferRecord',
fix(fixer) {
const { name } = node.id;
return fixer.replaceTextRange(
node.range,
`type ${name} = ${toRecord(index)};`,
);
},
});
},
};
},
});
126 changes: 126 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-record.test.ts
@@ -0,0 +1,126 @@
import rule from '../../src/rules/prefer-record';
import { RuleTester } from '../RuleTester';

const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
});

ruleTester.run('prefer-record', rule, {
valid: [
// Record
'type Foo = Record<string, any>;',

// Interface
'interface Foo {}',
`
interface Foo {
bar: string;
[key: string]: any;
}
`,
`
interface Foo {
[key: string]: any;
bar: string;
}
`,

// Type literal
'type Foo = {};',
`
type Foo = {
bar: string;
[key: string]: any;
};
`,
`
type Foo = {
[key: string]: any;
bar: string;
};
`,

// Generic
`
type Foo = Generic<{
[key: string]: any;
bar: string;
}>;
`,

// Function types
'function foo(arg: { [key: string]: any; bar: string }) {}',
'function foo(): { [key: string]: any; bar: string } {}',
],
invalid: [
// Interface
{
code: `
interface Foo {
[key: string]: any;
}
`,
output: `
type Foo = Record<string, any>;
`,
errors: [{ messageId: 'preferRecord', line: 2, column: 1 }],
},

// Type literal
{
code: 'type Foo = { [key: string]: any };',
output: 'type Foo = Record<string, any>;',
errors: [{ messageId: 'preferRecord', line: 1, column: 12 }],
},

// Generic
{
code: 'type Foo = Generic<{ [key: string]: any }>;',
output: 'type Foo = Generic<Record<string, any>>;',
errors: [{ messageId: 'preferRecord', line: 1, column: 20 }],
},

// Function types
{
code: 'function foo(arg: { [key: string]: any }) {}',
output: 'function foo(arg: Record<string, any>) {}',
errors: [{ messageId: 'preferRecord', line: 1, column: 19 }],
},
{
code: 'function foo(): { [key: string]: any } {}',
output: 'function foo(): Record<string, any> {}',
errors: [{ messageId: 'preferRecord', line: 1, column: 17 }],
},

// Never
// Type literal
{
code: 'type Foo = Record<string, any>;',
options: ['never'],
output: 'type Foo = { [key: string]: any };',
errors: [{ messageId: 'preferIndexSignature', line: 1, column: 12 }],
},

// Generic
{
code: 'type Foo = Generic<Record<string, any>>;',
options: ['never'],
output: 'type Foo = Generic<{ [key: string]: any }>;',
errors: [{ messageId: 'preferIndexSignature', line: 1, column: 20 }],
},

// Function types
{
code: 'function foo(arg: Record<string, any>) {}',
options: ['never'],
output: 'function foo(arg: { [key: string]: any }) {}',
errors: [{ messageId: 'preferIndexSignature', line: 1, column: 19 }],
},
{
code: 'function foo(): Record<string, any> {}',
options: ['never'],
output: 'function foo(): { [key: string]: any } {}',
errors: [{ messageId: 'preferIndexSignature', line: 1, column: 17 }],
},
],
});