8000
Bug: @typescript-eslint/no-unnecessary-type-assertion False positive on non-null assertion after an implicitly-any variable gets initialised inside a conditional or loop #11054
Labels
accepting prs
Go ahead, send a pull request that resolves this issue
bug
Something isn't working
package: eslint-plugin
Issues related to @typescript-eslint/eslint-plugin
Before You File a Bug Report Please Confirm You Have Done The Following...
Playground Link
https://typescript-eslint.io/play/#ts=5.8.2&fileType=.ts&code=GYVwdgxgLglg9mABAUwB4EMC2AHANsgCgEpEBvAKEUXykVQG5LEZhECBZdKACwDoAndGAAmcTMUQA%2BRAFoAjCQpUqqRAF5EAJkZUAvk37IoIfklQBCRAGpEcxvvJoseQkUZA&eslintrc=N4KABGBECmAeAu0B2ATAzpAXGA2uCUADgDYCuA5gJZKYAC8AnodGgMYBOlh8AtC8dXgB6dtFYB7ALaTkKaCh6NmPVgAsxAa3mR8AXQA0%2BSO1LEWWMMAC%2BIK0A&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eFYDAruuGAL4g9A&tokens=false
Repro Code
ESLint Config
tsconfig
Expected Result
No errors, since the non-null assertion (
!
) is necessary here; without it, tsc will refuse to compile the code, complaining that `'x' is possibly 'undefined'!Actual Result
Additional Info
Things that seem necessary to produce the error above:
x
is not explicitly typed when declared (so is implicitlyany
)x
takes place inside a conditional or a loop, and TypeScript therefore can't tell, without the non-null assertion, that the initial assignment is guaranteed to take placestrict: true
is enabledThe example code above is of course contrived, but a more realistic example where this would in fact be totally reasonable code would be one where, instead of an
if (...) {...}
that's guaranteed to run, the assignment takes place within a loop that's guaranteed to run (andx
gets used to store some sort of information about the final iteration of the loop that gets used after the loop finishes).The text was updated successfully, but these errors were encountered: