typescript-eslint / typescript-eslint

:sparkles: Monorepo for all the tooling which enables ESLint to support TypeScript
https://typescript-eslint.io
Other
15.12k stars 2.7k forks source link

Bug: [no-unnecessary-type-parameters] False positive on curried functions #9721

Closed eranhirsch closed 2 weeks ago

eranhirsch commented 1 month ago

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

Playground Link

https://typescript-eslint.io/play/#ts=5.5.4&showAST=types&fileType=.ts&code=C4TwDgpgBAYg9nAPAFQDRQMoD4oF5NQQAewEAdgCYDOUARFXALYQBGcFItAsAFBRQB%2BKMkIly1OnDIBjCNz6C6wOABsK8-gC46zDVG1kIANwgAnANy9eFCNJUBDU9ABmAVxnAAllKjOEKLAAKCntge21kAEptRGxAuGAACzNtDEi8HHgkNEwsSx4gA&eslintrc=N4KABGBEBOCuA2BTAzpAXGUEKQAIBcBPABxQGNoBLY-AWhXkoDt8B6Jge1tiacTJTIAhtEK0ipWsRFCAtonyJoqDJCXQO0SODABfELqA&tsconfig=N4KABGBEDGD2C2AHAlgGwKYCcDyiAuysAdgM6QBcYoEEkJemy0eAcgK6qoDCAFutAGsylBm3TgwAXxCSgA&tokens=false

Repro Code

type Foo<T, S> = S extends "somebody"
  ? T extends "once"
  ? "told"
  : "me"
  : never;

declare function foo<T>(data: T): <S>(other: S) => Foo<T, S>;

ESLint Config

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

tsconfig

No response

Expected Result

T shouldn't be surfaced by this rule; it has a meaningful usage in the type definitions.

Actual Result

T is surfaced as only being used once, incorrectly.

Additional Info

I maintain the Remeda typescript utility library. We rely heavily on curried functions, which are functions that return functions. The rule is firing for almost all our complex types where the type is passed on to the return type of the curried function. The non-curried functions, which are identical in terms of how the type param is used, are not falsely detected, so this has something to do with the param being passed on "through" to the return type of its returned function type.

When trying to reproduce this, I noticed that simpler cases where the T is used directly in the type aren't falsely detected; the issue can only be reproduced once we start introducing ternary conditions on other type params.

You can see a fuller example via the PR, which tries to introduce this rule into our codebase: https://github.com/remeda/remeda/pull/801

JoshuaKGoldberg commented 1 month ago

👍 good call on the conditional types, thanks for the note. Marking as accepting PRs with an added appreciation for the excellent Smash Mouth reference. 👌

JoshuaKGoldberg commented 1 month ago

...this is a funky one.

Conditional types are fun to work with.

bradzacher commented 1 month ago

AST check: context.sourceCode.getScope's references only lists the T in data: T, not Foo<T, S>.

In the playground I can see both references:

screenshot of scope analysis