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 have searched for related issues and found none that matched my issue.
- I have read the FAQ and my problem is not listed.
Playground Link
Repro Code
function example() {
let x;
if (Math.random() > -1) {
x = 2;
}
return x! + 1;
}
example();
ESLint Config
import tseslint from 'typescript-eslint';
export default tseslint.config(
tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
files: ['eslint.config.mjs'],
extends: [tseslint.configs.disableTypeChecked],
}
);
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
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 an if (...) {...}
that's guaranteed to run, the assignment takes place within a loop that's guaranteed to run (and x
gets used to store some sort of information about the final iteration of the loop that gets used after the loop finishes).
Metadata
Metadata
Assignees
Labels
Go ahead, send a pull request that resolves this issueGo ahead, send a pull request that resolves this issueSomething isn't workingSomething isn't workingIssues related to @typescript-eslint/eslint-pluginIssues related to @typescript-eslint/eslint-plugin