Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
Open
Description
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 havesearched for related issues and found none that matched my issue.
- I haveread the FAQ and my problem is not listed.
Playground Link
Repro Code
functionexample(){letx;if(Math.random()>-1){x=2;}returnx!+1;}example();
ESLint Config
importtseslintfrom'typescript-eslint';exportdefaulttseslint.config(tseslint.configs.recommendedTypeChecked,{languageOptions:{parserOptions:{projectService:true,tsconfigRootDir:import.meta.dirname,},},},{files:['eslint.config.mjs'],extends:[tseslint.configs.disableTypeChecked],});
tsconfig
{"include": ["**/*.ts"],"compilerOptions": {"strict":true, }}
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
6:10 error This assertion is unnecessary since it does not change the type of the expression @typescript-eslint/no-unnecessary-type-assertion
Additional Info
Things that seem necessary to produce the error above:
x
is not explicitly typed when declared (so is implicitlyany
)- the initial assignment of
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 place strict: true
is enabled
The 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 anif (...) {...}
that's guaranteed to run, the assignment takes place within aloop 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).