It turns out you can declare a variable in one case block and use it in another! At least in compile time anyway, at runtime it will throw an error or be undefined, depending on the interpreter implementation.
function processBranch(num) {
switch (num) {
case 1:
const text = "hello";
console.log("First branch:", text);
break;
case 2:
console.log("Second branch:", text);
break;
}
}
processBranch(1);
processBranch(2);
Needless to say, this is very stupid. The no-case-declarations ES Lint rule warns you when you declare a variable in a case branch, but it warns you always, even when you only use the declared variable in the case block which it was declared in, which is completely safe.
So, is there a compiler option for TypeScript that would solve this? Or a Babel plugin maybe? Or can the ES Lint rule be configured to correctly give warning only if you use the variable in a different case block than it was declared in?