Skip to content

Bug: [no-unnecessary-type-assertion] problem with asserting querySelector result #8388

@HolgerJeromin

Description

@HolgerJeromin

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=MYewdgzgLgBAZiEMC8MAmJgFcC2BTMKAOgCMQ0BPIgRyzwCcKBlPAGz2ChHoAoBYAFAwYAcgDEOCmzz5CMAHzoAlgDcRAGkEBKGAEMIMABIAVALIAZAKLtZsAD4wwWVqwDcgpXBg8EILYOFfImgKdiI0JQgAB1ZdChRREXcBQVBIWBJdegSMbFtScipaBmZpTm5%2BIVEJKRsCWEUItU0BLWTPb0z6fyqu4KhQvHDImLiEkSTBVPBoGEyALxzMXHqCyho6RhZ2cvoAHhMLaxl6%2BUrhcUlpWwVlZu12rx4FnuEF-sHh6Nj41AnkoA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUkACAXAngA4oDG0AlobgLQrzkB2uA9AwPbWwMOIkrIBDaPmoFi1AcmSJoucmwbooM6G2iQQ4MAF8Q2oA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

const foo = document.body.querySelector(
  '#myelement > div',
) as HTMLElement | null;  // This assertion is unnecessary since it does not change the type of the expression.

if (foo)
  foo.style.display = '';

const bar = document.body.querySelector(
  '#myelement > div',
);
if (bar)
  bar.style.display = ''; // failes because Element has no `style`

const baz = document.body.querySelector<HTMLElement>(
  '#myelement > div',
);
if (baz)
  baz.style.display = '';

ESLint Config

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

tsconfig

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

Expected Result

First example should not complain because the assertion changes the type.

Actual Result

There is an error "This assertion is unnecessary since it does not change the type of the expression." at the first example.

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    package: 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