Skip to content

[non-nullable-type-assertion-style] complains when casting to a type parameter that might be nullish #4512

Closed
@djcsdy

Description

@djcsdy
  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have read the FAQ and my problem is not listed.

Repro

{
  "rules": {
    "@typescript-eslint/non-nullable-typer-assertion-style": "error"
  }
}
function first<T>(array: ArrayLike<T>): T | null {
    return array.length > 0 ? (array[0] as T) : 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 with noUncheckedIndexedAccess, the type assertion array[0] as T is required because the original type of array[0] is T | 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 parameter T might itself be nullish. array[0]! is equivalent to array[0] as NonNullable<T>, which is not the same as array[0] as T.

To see the issue more clearly, consider the following slightly more contrived example:

function first<T extends string | null>(array: ArrayLike<T>): T | null {
    return array.length > 0 ? (array[0] as T) : null;
}

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 to array[0]! because the type parameter T has a constraint that explicitly allows the type to be null.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issuebugSomething isn't workingpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions