Skip to content

Function overloading based on string enum parameter. #14375

Closed
@realyze

Description

@realyze

[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"'.

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