Skip to content

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

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

Closed
asmundg opened this issue May 20, 2019 · 2 comments
Closed

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

asmundg opened this issue May 20, 2019 · 2 comments

Comments

@asmundg
Copy link
Member

asmundg commented May 20, 2019

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:

@dragomirtitian
Copy link
Contributor

Duplicate of #31456 ?

@asmundg
Copy link
Member Author

asmundg commented May 20, 2019

Yes, my bad. I forgot to look at closed issues.

@asmundg asmundg closed this as completed May 20, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants