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

Call to function returning never can not be used to narrow type #15991

Closed
bwrrp opened this issue May 22, 2017 · 4 comments
Closed

Call to function returning never can not be used to narrow type #15991

bwrrp opened this issue May 22, 2017 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@bwrrp
Copy link
Contributor

bwrrp commented May 22, 2017

TypeScript Version: 2.3.2

A function that never returns (return type never) can not be used in a type guard to narrow the type after the branch.

Code

class Thing { };

function diverges(): never {
    throw new Error('Never returns');
}

function problem(thing: Thing | null): Thing {
    if (thing === null) {
        diverges();
        // throw new Error('Works!');
    }

    return thing; // fails type check
}

Expected behavior:

Replacing the call to diverges() with a return or throw statement causes thing to be marked as type Thing after the branch, as code will never flow from the if (thing === null) branch to the code below. I expected a call to a function with return type never to achieve the same, as this should indicate that the call never returns.

Actual behavior:

The code does not compile due to an error, as the type of thing is not narrowed to Thing:
"Type 'Thing | null' is not assignable to type 'Thing'. Type 'null' is not assignable to type 'Thing'."

@krryan
Copy link

krryan commented May 22, 2017

I suspect this won't happen, because it is possible to return a never-type value, which means it's possible for that function to complete and return and control to move on down to return thing;.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 22, 2017
@RyanCavanaugh
Copy link
Member

Duplicate #12825. The recommended workaround is to write return diverges();

@RyanCavanaugh
Copy link
Member

I suspect this won't happen, because it is possible to return a never-type value

The intent of never is that it shouldn't be possible.

@bwrrp
Copy link
Contributor Author

bwrrp commented May 23, 2017

Sorry, must have missed that one in my search. Thanks for the explanation!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants