Skip to content

[no-unnecessary-type-constraint] fixing as suggested can lead to a TS error #3509

Closed
@nikolai-katkov

Description

@nikolai-katkov
  • 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/no-unnecessary-type-constraint": "error"
  }
}

Consider the following example:

const maybe = <T extends any>(whatever: T): T => {
  console.log(Object.keys(whatever)) // TS is complaining, which is good
  return whatever
}

It's dummy but it has a problem: calling maybe(null) will throw a runtime error (TypeError: Cannot convert undefined or null to object). Therefore I'd like Typescript to fail here. It does now, all good so far.

The rule no-unnecessary-type-constraint suggests replacing <T extends any> with <T>, because "Constraining the generic type `T` to `any` does nothing and is unnecessary."

So I change it to:

const maybe = <T>(whatever: T): T => {
  console.log(Object.keys(whatever)))
  return whatever
}

Result: TS is silent, the code is not safe against a runtime error.

Versions

package version
@typescript-eslint/eslint-plugin ^4.25.0
@typescript-eslint/parser ^4.25.0
TypeScript ^4.2.4
ESLint ^7.27.0
node 14.16.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuebugSomething 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