Skip to content

[prefer-reduce-type-parameter] fix results in invalid code #3584

@roikoren755

Description

@roikoren755
  • 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

{
  "rules": {
    "@typescript-eslint/prefer-reduce-type-parameter": 2
  }
}
declare const arr1: string[];
declare const arr2: string[];

const text = arr1.reduce<string>((acc) => acc, arr1.shift() as string);
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "allowJs": true,
    "declaration": true,
    "strict": true,
    "noImplicitAny": false,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "preserveSymlinks": true,
    "resolveJsonModule": true
  },
  "exclude": ["**/*.spec.ts", "**/*.spec.tsx", "**/__tests__", "**/dist/**/*"],
  "include": ["src/**/*", "index.ts"]
}

Expected Result

One of three options.
Either don't report this as an error, since the default value's type is string | undefined, and setting the reduce's type parameter as string leads to a TS error.

declare const arr1: string[];
declare const arr2: string[];

const text = arr1.reduce<string>((acc) => acc, arr1.shift() as string);

Or remove the type parameter from the reduce, and leave the one at the typecasting.

declare const arr1: string[];
declare const arr2: string[];

const text = arr1.reduce((acc) => acc, arr1.shift() as string);

Or, finally, remove the casting without breaking the code

declare const arr1: string[];
declare const arr2: string[];

const text = arr1.reduce<string>((acc) => acc, arr1.shift());

Actual Result

The fix turns the code into the following

declare const arr1: string[];
declare const arr2: string[];

const text = arr1.reduce<string><string>((acc) => acc, arr1.shift());

Additional Info

Versions

package version
@typescript-eslint/eslint-plugin 4.28.0
@typescript-eslint/parser 4.28.0
TypeScript 4.3.3
ESLint 7.29.0
node 14.15.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingpackage: 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