Use before declaration errors when using let statements within a switch case
See original GitHub issueTypeScript Version: 2.5.3
Code
function test(value) {
switch (value) {
case 1:
let foo = 10;
break;
case 2:
foo = 20; // Runtime ReferenceError: foo is not defined
break;
default:
}
}
test(2);
tsc --target es2015 (or higher)
Expected behavior:
This should probably produce a compile time error: Block-scoped variable 'pen' used before its declaration.
on reference to foo in case 2
.
Actual behavior:
The code type-checks and compiles fine, however, when running the es2015 transpiled output, you will receive a ReferenceError error at runtime. Ideally this type of error could be caught at compile time.
Issue Analytics
- State:
- Created 6 years ago
- Reactions:3
- Comments:9 (8 by maintainers)
Top Results From Across the Web
How to use a variable name declared with let inside multiple ...
This is what it should be. You declare it before the switch statement. Therefore, the variable is usable in every case beneath the...
Read more >let - JavaScript - MDN Web Docs
The let declaration declares a block-scoped local variable, optionally initializing it to a value.
Read more >Why can't variables be initialized in a switch statement?
So, the compiler reports an error that states that they are not sure whether this variable will be used in other cases and...
Read more >Declaring Variables in Switch Statements | Hampshire UK
You can still declare variables in switch statements, you just have to put curly brackets around the code after the case label.
Read more >Scoping variables in JavaScript switch statement
This shows that the case statements themselves are not blocks, variables declared within them are hoisted to the switch statement block. When ...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I’m trying to think of a reasonably-efficient algorithm to detect this and not coming up with many good ideas.
switch
isgoto
😕Update: Have something reasonable
Okay, I misread. Here’s one that would’ve been more obvious to me.