Skip to content

Function overloading based on string enum parameter. #14375

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

Closed
realyze opened this issue Mar 1, 2017 · 2 comments
Closed

Function overloading based on string enum parameter. #14375

realyze opened this issue Mar 1, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@realyze
Copy link

realyze commented Mar 1, 2017

[email protected]

I'd like to write a polymorphic function whose return type is inferred based on string enum value of a parameter.

Is there a way to do that?

Here's my - probably quite naive - approach (which doesn't compile):

type Test1 = 'foo';
type Test2 = 'bar';
type TUnion = Test1 | Test2;

interface TReturnForTest1 { }
interface TReturnForTest2 { }

function unionTypeTest(arg: Test1): TReturnForTest1;
function unionTypeTest(arg: Test2): TReturnForTest2;
function unionTypeTest(arg: TUnion): any {
    return null;
}

const bar = unionTypeTest('foo' as TUnion);  // Error: Type '"foo"' is not assignable to type '"bar"'.
@mhegazy
Copy link
Contributor

mhegazy commented Mar 1, 2017

function unionTypeTest(arg: Test1): TReturnForTest1;
function unionTypeTest(arg: Test2): TReturnForTest2;
function unionTypeTest(arg: Test1|Test2): TReturnForTest1 | TReturnForTest2;
function unionTypeTest(arg: TUnion): any {
    return null;
}

see #14337 for relevant discussion.

@mhegazy mhegazy added the Duplicate An existing issue was already created label Mar 1, 2017
@realyze
Copy link
Author

realyze commented Mar 1, 2017

@mhegazy Thanks for the reply! Not sure I grok the scalability concerns though. I'd expect tsc would just check the declarations from top to bottom and use the first one that matches, no? (i.e., linear w/r to number of declaration overloads). Doesn't seem unscalable to me.

@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 19, 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

2 participants