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

Allow extends type to be supertype of constraint types when narrowing conditional return type #61117

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

gabritto
Copy link
Member

@gabritto gabritto commented Feb 4, 2025

Before, we would not attempt to do return type narrowing for the following conditional type:

function voidRet<T extends { a: string } | undefined>(x: T): T extends {} ? void : T extends undefined ? number : never {
    if (x) {
        return;
    }
    return 1;
}

The reason was that the extends type {} was not identical to any element of the parameter union constraint type { a: string } | undefined.
This PR lifts the restriction, only requiring that a conditional's extends type be a supertype of an element of the parameter union constraint type. So now TS will attempt return type narrowing for the above example.

Note that just like the user is responsible for making sure the union components of the parameter type are disjoint types, the extends types in the conditional type also should be disjoint, or bad things can happen (see second example in the new test).

@typescript-bot typescript-bot added Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug labels Feb 4, 2025
@ehoogeveen-medweb
Copy link

Out of curiosity, does the following (object instead of {}) also work after this change?

function voidRet<T extends { a: string } | undefined>(x: T): T extends object ? void : T extends undefined ? number : never {
    if (x) {
        return;
    }
    return 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Author: Team For Uncommitted Bug PR for untriaged, rejected, closed or missing bug
Projects
Status: Not started
Development

Successfully merging this pull request may close these issues.

3 participants