Skip to content

[no-unnecessary-type-assertion] False negative if type is temporarily narrowed but narrowing is never relied on #2953

@peterflynn

Description

@peterflynn

This is probably more of an enhancement request...

  • 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-assertion": "error"
  }
}
let x: string | undefined = Math.random() > 0.5 ? "yes" : undefined;
let y: string | undefined = undefined;

if (Math.random() > 0.5) {
    y = x!;
}

if (y !== undefined) {
    console.log("Not undefined");
}

Expected Result

Expected:
"This assertion is unnecessary since the receiver accepts the original type of the expression."

By all appearances, the ! postfix is unnecessary since it's being assigned right back to a nullable variable again.

Actual Result

No error.

This happens because inside the scope of the if, the type of y is narrowed to exclude undefined. If there were more code inside that block, it could rely on y being non-null without TSC complaining.

However, in cases like this where there isn't any more code inside the block, there's nothing relying on that narrowing -- everything would compile just as successfully with the ! operator removed.

Additional Info

The rule correctly flags simpler examples where there is no temporary type narrowing -- like this one (from #1310):

let x: string | undefined = Math.random() > 0.5 ? "yes" : undefined;
let y: string | undefined = x!;

The more complex example above may be a harder scenario to detect, but it does still fit the bill as "unnecessary," IMHO.

Versions

package version
@typescript-eslint/eslint-plugin 4.1.0
@typescript-eslint/parser 4.1.0
TypeScript 3.9.7
ESLint 7.12.1
node 12.18.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinggood first issueGood for newcomerspackage: 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