Skip to content

Type guard not working in unreachable code #30358

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
hraban opened this issue Mar 13, 2019 · 2 comments
Closed

Type guard not working in unreachable code #30358

hraban opened this issue Mar 13, 2019 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@hraban
Copy link

hraban commented Mar 13, 2019

TypeScript Version:

ts@next (Version 3.4.0-dev.20190313)

Search Terms:

typescript
typeguard
type guard
unreachable
undefined
defeat

any permutation thereof

Code

// Please enable TSC option strictNullChecks

function onereturn(y: string | undefined) {
    if (!y) {
        throw new Error();
    }
    // No error: great.
    return y.length;
}

function tworeturn(y: string | undefined) {
    return 3; // temporarily disable function
    if (!y) {
        throw new Error();
    }
    // Why does this now error?
    return y.length;
}

Expected behavior:

Either:

  • Consistent type checking regardless of unreachability, or
  • a "code unreachable" error.

I don't think the unreachable version should necessarily be error free. I just think the current way of erroring is very unintuitive and confusing.

Actual behavior:

The type guard only works if the code is reachable. Otherwise, it stops working, and the error only shows up when you use the variable further downstream as if the type guard had worked.

Playground Link:

https://www.typescriptlang.org/play/#src=%2F%2F%20Please%20enable%20TSC%20option%20strictNullChecks%0D%0A%0D%0Afunction%20onereturn(y%3A%20string%20%7C%20undefined)%20%7B%0D%0A%20%20%20%20if%20(!y)%20%7B%0D%0A%20%20%20%20%20%20%20%20throw%20new%20Error()%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%2F%2F%20No%20error%3A%20great.%0D%0A%20%20%20%20return%20y.length%3B%0D%0A%7D%0D%0A%0D%0Afunction%20tworeturn(y%3A%20string%20%7C%20undefined)%20%7B%0D%0A%20%20%20%20return%203%3B%0D%0A%20%20%20%20if%20(!y)%20%7B%0D%0A%20%20%20%20%20%20%20%20throw%20new%20Error()%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%2F%2F%20Why%20does%20this%20still%20error%3F%0D%0A%20%20%20%20return%20y.length%3B%0D%0A%7D

Related Issues:

Couldn't find anything related in bug tracker.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Mar 14, 2019
@RyanCavanaugh
Copy link
Member

Duplicate #26914

@hraban
Copy link
Author

hraban commented Mar 15, 2019 via email

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

2 participants