Skip to content

Union types do not match narrowed overloads #46778

@Haringat

Description

@Haringat

Bug Report

I am not sure if this is a bug or a design limitation, but when you have a function with narrowed overloads (see example) you cannot call the function with a broader union type although the union type does not go out of bounds of the overloads.

🔎 Search Terms

union types overloads

🕗 Version & Regression Information

  • I was unable to test this on prior versions because of time restraints

⏯ Playground Link

Simplified example

💻 Code

function isOneOrTwo(it: unknown): it is (1 | 2) {
    return it === 1 || it === 2;
}

function doSomething(it: unknown) {
    if (isOneOrTwo(it)) {
        return doSomethingElse(it);
    } else {
        throw new Error("out of range");
    }
}

function doSomethingElse(it: 1): "one";
function doSomethingElse(it: 2): "two";
function doSomethingElse(it: number) {
    switch (it) {
        case 1:
            return "one";
        case 2:
            return "two";
        default:
            throw new Error("out of range");
    }
}

🙁 Actual behavior

The compiler reports an error on the call to doSomethingElse because the union type is not assignable to either of the overloads.

🙂 Expected behavior

The function is callable and returns a union type of the relevant overload's return values.

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