Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

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

Description

@djcsdy
  • 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

packageversion
@typescript-eslint/eslint-plugin5.10.2
@typescript-eslint/parser5.10.2
TypeScript4.5.5
ESLint8.8.0
node16.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


      [8]ページ先頭

      ©2009-2025 Movatter.jp