-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Description
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 |