Skip to content

[non-nullable-type-assertion-style] false positive when using type assertion to specify type #2887

@yangmingshan

Description

@yangmingshan
  • 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-type-assertion-style": "error"
  }
}
function inject<T>(key: string): T | undefined {
  // ...
}

// Of course, I can write it to `const str = inject<string>('myString')!`, but still seems a bug.
// Autofix will fix it to `const str = inject('myString')!`, and might break type check.
const str = inject('myString') as string

tsconfig

{
  "compilerOptions": {
    "target": "esnext",
    "lib": ["esnext"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noFallthroughCasesInSwitch": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true
  }
}

Expected Result

No error.

Actual Result

Use a ! assertion to more succintly remove null and undefined from the type.

Additional Info

Versions

package version
@typescript-eslint/eslint-plugin 4.10.0
@typescript-eslint/parser 4.10.0
TypeScript 4.1.3
ESLint 7.15.0
node 15.4.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    package: eslint-pluginIssues related to @typescript-eslint/eslint-pluginwontfixThis will not be worked onworking as intendedIssues that are closed as they are working as intended

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions