Skip to content

Bug: [no-unnecessary-type-assertion] false positive when using non-null assertion (!) on inferred type #11559

@szhsin

Description

@szhsin

Before You File a Bug Report Please Confirm You Have Done The Following...

  • I have tried restarting my IDE and the issue persists.
  • I have updated to the latest version of the packages.
  • I have searched for related issues and found none that matched my issue.
  • I have read the FAQ and my problem is not listed.

Playground Link

https://typescript-eslint.io/play/#ts=5.9.2&fileType=.tsx&code=C4TwDgpgBAIghsOAeAKgPigXigbygNzgBsBXCAfgC4oUoBfAbgChRIoA1YslcCVeRBmwoBcKBAAewCADsAJgGdYCZAEsZAMwgAnGhnI0o1GRHw7mTSWAD224FADG1mQvsbr1rFH4rxU2YrKiEhwMiBoaAAUcirUIioAlFgYOExQjs6uUADmEMCcpNDYkUmYGDGIAHSEhVBwSgXcvD6CUAA%2BUCTyEBrqEHLM6U4u9jVk1I0QPJAtcEI5eZMlAISDUNp5JNoyBFwQzIxAA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0ipWkOTJE0fJQ5N0UOdA7RI4MAF8QOoA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

type Data<T> = { value?: T };
type ValueType<TData> = TData extends Data<infer T> ? T : never;

export const foo = <TData extends Data<any>>(data: TData) => {
  const getValue = () => data.value as ValueType<TData> | undefined;
  const value: ValueType<TData> = getValue()!;
  return value;
};

ESLint Config

module.exports = {
  parser: "@typescript-eslint/parser",
  rules: {
    "@typescript-eslint/no-unnecessary-type-assertion": "error"
  },
};

tsconfig

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

Expected Result

No error

Actual Result

The linter reports an error: "This assertion is unnecessary since the receiver accepts the original type of the expression."
However, if I remove the non-null assertion !, TypeScript complains.

Additional Info

The error disappears if I change Data<any> to Data<unknown> in the function (foo’s) type parameter, but in my case I need it to remain any for other reasons.

This also shows up in a real-world scenario, for example here

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingpackage: eslint-pluginIssues related to @typescript-eslint/eslint-plugintriageWaiting for team members to take a look

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions