New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[no-unnecessary-type-assertion] False negative if type is temporarily narrowed but narrowing is never relied on #2953
Comments
typescript-eslint/packages/eslint-plugin/src/rules/no-unnecessary-type-assertion.ts Line 163 in 55111af
This line asks TS for the contextual type of the non-null expression - which means it is attempting to get the type that TS thinks it's assigning to. This is a gap in the handling of our function: typescript-eslint/packages/eslint-plugin/src/util/types.ts Lines 477 to 512 in e7528e6
Should be simple enough to fix up. |
@peterflynn are you working on this? If not I'd love to give it a shot tonight, thanks 😄 |
We're going to have to rollback this change. However what you may not realise is that this actually changes the control-flow of the rest of the code. Here is an example: let x: number | undefined;
let y: number | undefined;
// typeof y === number | undefined
y = x;
// typeof y === number | undefined
// error: Object is possibly 'undefined'.(2532)
(y + 1);
y = x!;
// typeof y === number !!!!!!!!
// no error below
(y + 1); |
This is probably more of an enhancement request...
Repro
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 ofy
is narrowed to excludeundefined
. If there were more code inside that block, it could rely ony
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):
The more complex example above may be a harder scenario to detect, but it does still fit the bill as "unnecessary," IMHO.
Versions
@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
The text was updated successfully, but these errors were encountered: