Skip to content

Type inference when a function is overloaded and the input param is a union of possible inputs #14337

Closed
@ofirgeller

Description

@ofirgeller

If we define a function and two interfaces like this:

    interface A {

    }

    interface B {

    }

    func(type: 'A'): A;
    func(type: 'B'): B;
    func(type: string) {
     /// this function returns an object of type A or B depending on the string input
    }

I would like to be able to call the function like this

var input = <"A"|"B">getInput();
var output = func(input);

And have the return type be A | B. it seems to me this is logicaly consistent. No idea if it is hard to implement.

Syntactic
Does not change the syntax.

Semantic
Error TS2345 Argument of type '"A" | "B"' is not assignable to parameter of type '"B"'.
Type '"A"' is not assignable to type '"B"'.

The compiler is checking if all possible types of input match all the overloads, when in fact we just need
each type to match a single overload.

Emit
No change past the point of inference.

Compatibility
Should not break anything as this example code does not compile at the moment

Other
Can the feature be implemented without negatively affecting compiler performance?
Might even make it marginally faster as we can stop checking when we find the first overload matching the first type in the union and move on to the next.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Working as IntendedThe behavior described is the intended behavior; this is not a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions