Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong overload inferred in generic function #40413

Closed
clo4 opened this issue Sep 7, 2020 · 1 comment
Closed

Wrong overload inferred in generic function #40413

clo4 opened this issue Sep 7, 2020 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@clo4
Copy link

clo4 commented Sep 7, 2020

TypeScript Version: 4.0.2

Search Terms:

  • Overload inference
  • Overload resolution
  • Generic function overloaded

Expected behavior:
T gets inferred from value, should resolve overloaded to the most appropriate signature ((x: number) => number)

Actual behavior:
T is inferred from final signature of overloaded.

Related Issues:

Code

declare function overloaded(x: number): number;
declare function overloaded(x: string): string;

declare function wonky<T>(value: T, func: (x: T) => T): void;

wonky(1, overloaded)
//    ^-- Argument of type 'number' is not assignable to parameter of type 'string'.

// Maybe shouldn't resolve a type from a function with overloads unless there's
// no other option?

It's not pretty, but it can be worked around by forcing T to be inferred from value.

declare function wonky<T, _T extends T>(value: T, func: (x: _T) => _T): void;

wonky(1, overloaded)
// function wonky<number, number>(value: number, func: (x: number) => number): void
Output
"use strict";
wonky(1, overloaded);
Compiler Options
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "strictBindCallApply": true,
    "noImplicitThis": true,
    "noImplicitReturns": true,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "removeComments": true,
    "declaration": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "moduleResolution": 2,
    "target": "ES2017",
    "jsx": "React",
    "module": "ESNext"
  }
}

Playground Link: Provided

@RyanCavanaugh
Copy link
Member

RyanCavanaugh commented Sep 9, 2020

Duplicate #32418; generic inference is limited to "last overload" in most cases. Overloads, whenever possible, should always have a final overload that covers all of the cases in a more general way.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 9, 2020
@clo4 clo4 closed this as completed Sep 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants