8000 Function overloading - obscure logic · Issue #22231 · microsoft/TypeScript · GitHub
[go: up one dir, main page]

Skip to content
Function overloading - obscure logic #22231
Closed
@evil-shrike

Description

@evil-shrike

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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0