Skip to content

Union type incorrectly narrowed to only default value type in catch block #29670

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
mvachhar opened this issue Jan 31, 2019 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@mvachhar
Copy link

mvachhar commented Jan 31, 2019

TypeScript Version: 3.2.2 (However, I believe it exists in typescript@next as well)

Search Terms:
Incorrect type narrowing in catch
type narrowing union catch
type narrowing union default
union default incorrect type

Code

function otherWork() { throw new Error("Hi!"); }
function getNum() { return 3; }

function foo() {
    let x: number | null = null;
    try {
        x = getNum();
        otherWork();
    } catch (e) {
        console.log(x && x.toString()); //Error, type of x is null, not number | null
    }
    x;
}

Expected behavior:
The type of the first x in console.log(x && x.toString()) should have type number | null, the second x in x.toString() should have type number.
Actual behavior:
The first x has type null, the second x has type never (as expected if the first x has type null). The type of the last x, in x; has the correct type number | null

Playground Link:
https://typescript-play.js.org/#code/GYVwdgxgLglg9mABHKALApgJwOp0wawAoBKRAb0TUzgHdEx06BRTazQgIgAkYBCD4gG5EAXwBQoSLASIA5uigA5EAFsS5RJgUhMSAMzDxE8NHhJgcOOrJjEdxABsFiAB4AueqoBGWRAB9PBwdEAF5Ah0FbeyhMAE9yKPt7F1C5BWU1IUSk5DQsXAISSKSRRAgAQygIVERCdFIbHPsIBABnOCcAOgc4WUIUgDIB106oOABlGJgwPuIhRAB6BZY2ABpKWIAHdGRgV0QYVvD1sBRPFR9Mf3Ds8SSXSJEgA

Related Issues:
None

@ajafff
Copy link
Contributor

ajafff commented Feb 1, 2019

This should be fixed in typescript@next with a recent PR by @weswigham

@mvachhar
Copy link
Author

mvachhar commented Feb 1, 2019

I don't know enough about the ts compiler to know for sure, but it does appear that the PR to fix #28153 should also fix this. Should this be marked as a dup of #28153?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 5, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

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

No branches or pull requests

4 participants