Skip to content

[consistent-indexed-object-style] Readonly modifier is ignored #2797

Closed
@ryym

Description

@ryym
  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have read the FAQ and my problem is not listed.

Repro

{
  "root": true,
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/consistent-indexed-object-style": "error"
  }
}
export type ReadonlyValues = {
  readonly [key: string]: number;
};

export const useValues = (vals: ReadonlyValues): void => {
  // @ts-expect-error
  vals.foo = 123;
};

tsconfig.json:

{
  "include": ["src"],
  "compilerOptions": {
    "noEmit": true,
    "strict": true
  }
}

Expected Result

ESLint reports no error. An index signature with readonly modifier cannot be converted to a Record type since the properties of Record type are not readonly.

Actual Result

ESLint reports an error.

$ npx eslint src/repro.ts

/private/tmp/repro/src/repro.ts
  1:30  error  A record is preferred over an index signature  @typescript-eslint/consistent-indexed-object-style

✖ 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

And fixing this error by eslint --fix makes the TypeScript compilation fail because now it is valid to assign a new value to vals.foo.

$ npx tsc
$ npx eslint --fix src/repro.ts
$ npx tsc
src/repro.ts(4,3): error TS2578: Unused '@ts-expect-error' directive.

Diff made by eslint --fix:

diff --git a/src/repro.ts b/src/repro.ts
index c64cb05..0971227 100644
--- a/src/repro.ts
+++ b/src/repro.ts
@@ -1,6 +1,4 @@
-export type ReadonlyValues = {
-  readonly [key: string]: number;
-};
+export type ReadonlyValues = Record<string, number>;
 
 export const useValues = (vals: ReadonlyValues): void => {
   // @ts-expect-error

Versions

package version
@typescript-eslint/eslint-plugin 4.8.1
@typescript-eslint/parser 4.8.1
TypeScript 4.1.2
ESLint 7.14.0
node 10.15.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghas prthere is a PR raised to close thispackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions