Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.8k
Description
- I have tried restarting my IDE and the issue persists.
- I have updated to the latest version of the packages.
- I haveread the FAQ and my problem is not listed.
Repro
{"rules": {"@typescript-eslint/non-nullable-typer-assertion-style":"error" }}functionfirst<T>(array:ArrayLike<T>):T|null{returnarray.length>0 ?(array[0]asT) :null;}
tsconfig:
"compilerOptions": {"target":"es5","module":"commonjs","strict":true,"noUncheckedIndexedAccess":true },
Expected Result
typescript-eslint should not report any errors.
Actual Result
typescript-eslint complains about this type assertion:array[0] as T:
Use a ! assertion to more succintly remove null and undefined from the type @typescript-eslint/non-nullable-type-assertion-style
Additional Info
When compiling withnoUncheckedIndexedAccess, the type assertionarray[0] as T is required because the original type ofarray[0] isT | undefined.
However, non-nullable-type-assertion-style complains about the cast, suggesting that it should bearray[0]! instead. This is not correct because the type parameterT might itself be nullish.array[0]! is equivalent toarray[0] as NonNullable<T>, which is not the same asarray[0] as T.
To see the issue more clearly, consider the following slightly more contrived example:
functionfirst<Textendsstring|null>(array:ArrayLike<T>):T|null{returnarray.length>0 ?(array[0]asT) :null;}
non-nullable-type-assertion-style complains about this code too, but here the problem is more obvious. Clearly the type assertionarray[0] as T is not equivalent toarray[0]! because the type parameterT has a constraint that explicitly allows the type to benull.
See#4509 for a fix
Versions
| package | version |
|---|---|
@typescript-eslint/eslint-plugin | 5.10.2 |
@typescript-eslint/parser | 5.10.2 |
TypeScript | 4.5.5 |
ESLint | 8.8.0 |
node | 16.13.2 |