[non-nullable-type-assertion-style] complains when casting to a type parameter that might be nullish #4512
Closed
3 tasks done
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
Repro
tsconfig:
Expected Result
typescript-eslint should not report any errors.
Actual Result
typescript-eslint complains about this type assertion:
array[0] as T
:Additional Info
When compiling with
noUncheckedIndexedAccess
, 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 be
array[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:
non-nullable-type-assertion-style complains about this code too, but here the problem is more obvious. Clearly the type assertion
array[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
@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
The text was updated successfully, but these errors were encountered: