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

Function overloading - obscure logic #22231

Closed
evil-shrike opened this issue Feb 28, 2018 · 2 comments
Closed

Function overloading - obscure logic #22231

evil-shrike opened this issue Feb 28, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@evil-shrike
Copy link

evil-shrike commented Feb 28, 2018

I have a variable of a union type (A or B). I have a function with overloads for A and for B.
It seems definitely sensible to allow passing this variable to the function. But TS fails on compilation.

interface A { foo: string };
interface B { bar: string };
let value: A | B;

function test(obj: A): boolean;
function test(obj: B): boolean;
function test(obj) { return true; }

test(value);

See Playground

Expected behavior:
No compile errors.

Actual behavior:

lib.ts(28,6): error TS2345: Argument of type 'A | B' is not assignable to parameter of type 'B'.
  Type 'A' is not assignable to type 'B'.
    Property 'bar' is missing in type 'A'.

I didn't test on all versions but I guess it doesn't depend on particular version as it's failing in the Playground.

I understand that instead of using overloads I can create a function with union type for argument:

function test(obj: A | B): boolean;

but in my case it's not acceptable. Actually the provided code is a simplified example of bigger problem.
I have a component with an option which type is string[] | Map<string> where Map is

export interface Map<T> {
	[key: string]: T;
}

I need to pass this option to a function from Undescore like these ones:

contains<T>(list: _.List<T>, value: T): boolean;
contains<T>(object: _.Dictionary<T>, value: T): boolean;
@s-ve
Copy link

s-ve commented Feb 28, 2018

Duplicate of #14107 ?

@ghost ghost added the Duplicate An existing issue was already created label Feb 28, 2018
@evil-shrike
Copy link
Author

@s-ve yes, I guess so

@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants