Skip to content

Type inferences with overloads have failed #10645

Closed

Description

TypeScript Version: master

Code

function f<a, b>(g: (a: a) => b, a: a): b {
  return g(a);
}
var g = <{(data: number): number; (data: string): string;}>((p: number) => p);
f(g, ''); // string
f(g, 0); // error, should return number

Expected behavior:

$ node built/local/tsc.js --noEmit --lib es6 --strictNullChecks --noImplicitAny index.ts

Actual behavior:

$ node built/local/tsc.js --noEmit --lib es6 --strictNullChecks --noImplicitAny index.ts
index.ts(6,1): error TS2453: The type argument for type parameter 'a' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
  Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number'.

Activity

  1. mhegazy commented on Aug 31, 2016

    @mhegazy
    Contributor
  2. falsandtru commented on Oct 1, 2016

    @falsandtru
    ContributorAuthor

    any updates?

  3. sandersn commented on Oct 3, 2016

    @sandersn
    Member

    No, I haven't had a chance to look at this yet.

  4. sandersn commented on Oct 13, 2016

    @sandersn
    Member

    This is, unfortunately, how TypeScript is intended to treat overloads during type inference. Type inference is not smart enough to infer an overloaded call signature, so it just chooses the last one. If you reverse the order of declarations, you will see that the error switches to the other call.

    Adapted from the spec, section 3.10.6 (Type Inference):

    When comparing call signatures, signatures in S correspond to signatures in T pairwise in declaration order. If S and T have different numbers of signatures, the excess first signatures in declaration order of the longer list are ignored.

    In the example code, S is { (data: number): number; (data: string) => string } and T is { (a: a) => b }. That means that type inference always returns a=string, b = string.

  5. added
    Working as IntendedThe behavior described is the intended behavior; this is not a bug
    SpecIssues related to the TypeScript language specification
    on Oct 13, 2016
  6. falsandtru commented on Oct 13, 2016

    @falsandtru
    ContributorAuthor

    I see, thx!

  7. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugA bug in TypeScriptSpecIssues related to the TypeScript language specificationWorking as IntendedThe behavior described is the intended behavior; this is not a bug

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions