Typescript: Switch block: Cannot redeclare block-scoped variable

Created on 14 Nov 2016  路  3Comments  路  Source: microsoft/TypeScript

TypeScript Version: 2.0.3, target: es5 or es6:

switch (s) {
        case 0:
            let v = "v.1";
            return v;

        case 1:
            let v = "v.2";
            return v;
    }

Actual behavior:
Cannot redeclare block-scoped variable 'v'

__Playground__: replay


It seems like a variable scope mess, but most JavaScript engines will ignore second variable declaration let (no strict mode) and will run the output script correctly.

Will it be good if every case statement outputs by default its own block {} in JS? The next code will be compiled with TSC:

switch (s) {
        case 0:
                {
            let v = "v.1";
            return v;
                }
        case 1:
               {
            let v = "v.2";
            return v;
               }
    }

Working as Intended

Most helpful comment

Is this intentionally part of the spec? Seems strange...

Note that wrapping the case contents in curly braces correctly defines the scope so this error doesn't occur.

All 3 comments

current behavior is per ES spec. This code yields an error in Node 7, Chrome and Edge:

function f(s) {
    switch (s) {
        case 0:
            let v = "v.1";
            return v;

        case 1:
            let v = "v.2";
            return v;
    }
}

Indeed, ES7 states it clearly, sorry for a wrong issue.

BTW, I used var keyword to test in browsers and most of them know how to run it correctly, while let produces the error due the implementation of ES6+ specs.

Is this intentionally part of the spec? Seems strange...

Note that wrapping the case contents in curly braces correctly defines the scope so this error doesn't occur.

Was this page helpful?
0 / 5 - 0 ratings