0

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?

kajacx
  • 12,361
  • 5
  • 43
  • 70
  • Typescript 4.5.5 correctly identifies this as a `TS2454 - Variable is used before being assigned` during compile. What version of TS are you using? I've just gone back a major version and quite a few minors and haven't found one yet that doesn't error in this example. – David Barker Sep 13 '22 at 06:54
  • We are using Typescript 4.4.4, but we have strict mode turn off (unfortunately), so maybe it is because of that. Anyway, forcing a new lexical scope by adding a pair of `{}` brackets solves the problem. The ESLint rule can then remind you to add the brackets. – kajacx Sep 13 '22 at 06:59
  • 1
    Yeah, with strict mode off the error does go away on compile. And yes adding a lexical scope to the variable declaration does cause errors to appear. I agree with you, quite annoying and actually a bit dumb even for non strict mode. One of the many reasons strict mode shouldn't really be an option to turn on or off IMO. – David Barker Sep 13 '22 at 07:05

0 Answers0