Skip to content

Improve conditional type constraints#23039

Merged
ahejlsberg merged 3 commits into
masterfrom
fixConditionalConstraints
Mar 31, 2018
Merged

Improve conditional type constraints#23039
ahejlsberg merged 3 commits into
masterfrom
fixConditionalConstraints

Conversation

@ahejlsberg
Copy link
Copy Markdown
Member

@ahejlsberg ahejlsberg commented Mar 30, 2018

This PR improves our reasoning over constraints associated with conditional types. We now consider a conditional type of the form T extends U ? T : X to have the constraint (T & U) | F (meaning that T extends U ? T : X is assignable to anything to which (T & U) | F is assignable). Previously we considered the constraint to just be T | F, but we now factor in the relationship to U that has been proven by the extends clause.

With this change the predefined Extract<T, U> conditional type effectively becomes a way of representing a type T with an additional constraint U. Or, in more intuitive terms, a T that is also known to be a U. For example:

function isFunction<T>(value: T): value is Extract<T, Function> {
    return typeof value === "function";
}

// Return type is Extract<T, Function>, i.e. a T known to be a Function
function getFunction<T>(item: T) {
    if (isFunction(item)) {
        return item;
    }
    throw new Error();
}

function f1<T>(x: T) {
    if (isFunction(x)) {
        const f: Function = x;  // x is a Function
        const t: T = x;  // and x is a T
    }
}

function f2(x: string | (() => string) | undefined) {
    if (isFunction(x)) {
        x();  // x narrowed to () => string
    }
}

function f3(x: string | (() => string) | undefined) {
    const f = getFunction(x);  // () => string
    f();
}

Fixes #22899.

@ahejlsberg ahejlsberg merged commit b382952 into master Mar 31, 2018
@ahejlsberg ahejlsberg added this to the TypeScript 2.8.2 milestone Mar 31, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 25, 2018
@ahejlsberg ahejlsberg deleted the fixConditionalConstraints branch May 24, 2019 13:57
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants