Typescript: Bug: Switch case statements allow use of undeclared variables

Created on 24 Sep 2017  Â·  6Comments  Â·  Source: microsoft/TypeScript

Discovered a bug in my code and was surprised TS didn't catch it for me. It doesn't seem like this is allowed (in Chrome 60, at least).

TypeScript Version: 2.2.4

Code

var baz: number = 2
switch (baz) {
  case 1:
    let foo = 'bar'
    break;
  case 2:
    document.write(foo)
    break;
}

Playground: link

Expected behavior:

TS should warn/error in second case statement that foo is not declared.

Actual behavior:

TS does not throw an error and foo is undefined

If this is expected/by design, I'm interested to know why (and if there's a way to catch it).

Working as Intended

Most helpful comment

If you turn on strictNullChecks then TypeScript will correctly report that foo is used before it's assigned to.

All 6 comments

If you turn on strictNullChecks then TypeScript will correctly report that foo is used before it's assigned to.

So there are situations where this could be valid, I take it?

It is valid, since switch statements are a single block. If you had another let foo in another case you would get a redeclaration error. So string null checks is appropriate.

My advice would be to use a block for every case statement that introduces new variables. The block will create a separate scope.

var baz: number = 2
switch (baz) {
    case 1: {
        let foo = 'bar'
        break;
    }
    case 2:
        document.write(foo)  // error as expected
        break;
}

Ah, okay, that makes more sense now! Thanks.

On Sun, Sep 24, 2017, 05:35 Marin Marinov notifications@github.com wrote:

My advice would be to use a block for every case statement that
introduces new variables. The block will create a separate scope.

var baz: number = 2switch (baz) {
case 1: {
let foo = 'bar'
break;
}
case 2:
document.write(foo) // error as expected
break;
}

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/Microsoft/TypeScript/issues/18720#issuecomment-331701265,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAiaawNA964wwrsQHwEPbzNFF6x9VGZCks5sljB1gaJpZM4Phve_
.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings