Skip to content

Narrowing union of generic and null to null does not work #31473

Closed
@asmundg

Description

@asmundg

TypeScript Version: 3.5.0-dev.20190518

Search Terms: narrow generic

Code

const isNull = (_: null): true => true;

const fails = <T>(arg: T | null): T => {
    if (arg != null) {
        // arg is T
        return arg;
    } else {
        // 3.4.5: arg is null
        // 3.5.0-dev.20190518: Argument of type 'T | null' is not assignable to parameter of type 'null'.
        //                       Type 'T' is not assignable to type 'null'.
        isNull(arg);
        throw new Error();
    }
};

Expected behavior:

With strict null checking, narrowing arg: T | null to T works. The else case of arg != null should narrow to arg: null.

Actual behavior:

In the else case, arg is not narrowed at all. This works as expected in 3.4.5, but appears to have regressed in 3.5.0.

Playground Link: http://www.typescriptlang.org/play/#src=%0D%0Aconst%20isNull%20%3D%20(_%3A%20null)%3A%20true%20%3D%3E%20true%3B%0D%0A%0D%0Aconst%20fails%20%3D%20%3CT%3E(arg%3A%20T%20%7C%20null)%3A%20T%20%3D%3E%20%7B%0D%0A%20%20%20%20if%20(arg%20!%3D%20null)%20%7B%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20arg%20is%20T%0D%0A%20%20%20%20%20%20%20%20return%20arg%3B%0D%0A%20%20%20%20%7D%20else%20%7B%0D%0A%20%20%20%20%20%20%20%20%2F%2F%203.4.5%3A%20arg%20is%20null%0D%0A%20%20%20%20%20%20%20%20%2F%2F%203.5.0-dev.20190518%3A%20Argument%20of%20type%20'T%20%7C%20null'%20is%20not%20assignable%20to%20parameter%20of%20type%20'null'.%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20Type%20'T'%20is%20not%20assignable%20to%20type%20'null'.%0D%0A%20%20%20%20%20%20%20%20isNull(arg)%3B%0D%0A%20%20%20%20%20%20%20%20throw%20new%20Error()%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%3B%0D%0A

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions