Skip to content

Bug: [no-unnecessary-type-assertion] False positive where removing the type assertion leads to TS error #7207

@marcelgerber

Description

@marcelgerber

Before You File a Bug Report Please Confirm You Have Done The Following...

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have searched for related issues and found none that matched my issue.
  • I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.1.6&fileType=.tsx&code=DYUwLgBMCWCioFsQDswGcBcEASAVAsgDKECS8ISqA2gLoBQdokIiaEAvBAIIBOPAhgE8AdADMeAewQAKACYSAxgFdKYYQEclIHoIDKLEArASeXYMGkAiflGiWAlPYj82eIqXKrajOIhToOCAMENCA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0ipWkOTJE0fJQ5N0UOdA7RI4MAF8QOoA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

let liElements: HTMLLIElement[]

let elems = Array.from(document.querySelectorAll("a li")) as HTMLLIElement[]
liElements = elems

ESLint Config

module.exports = {
  parser: "@typescript-eslint/parser",
  rules: {
    "@typescript-eslint/no-unnecessary-type-assertion": "error"
  },
};

tsconfig

{
  "compilerOptions": {
    // ...
  }
}

Expected Result

I expected no error to appear here, since removing the as HTMLLIElement leads to a TS error.

Actual Result

TSEslint suggests removing the as HTMLLIElement (including auto-fixing it), which then leads to a TypeScript error in line 4:

Type 'Element[]' is not assignable to type 'HTMLLIElement[]'.
  Type 'Element' is missing the following properties from type 'HTMLLIElement': type, value, accessKey, accessKeyLabel, and 119 more.(2322)
let liElements: HTMLLIElement[]

Additional Info

package version
@typescript-eslint/eslint-plugin 6.0.0
@typescript-eslint/parser 6.0.0
TypeScript 5.1.6
ESLint 8.39.0
node web

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingpackage: eslint-pluginIssues related to @typescript-eslint/eslint-pluginworking as intendedIssues that are closed as they are working as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions