TypeScript: how to throw an error w/o the compiler being smart about reachability?

Viewed 25

In the midst of programming I often want to throw an error explicitly just to see how the surrounding code would behave in that case. To see if error handling behaves as intended.

However, a definite throw new Error('foo') changes how the compiler looks at subsequent code: because it tries to be smart about reachability it would then often consider subsequent code to not be reached, and then usually fail to compile as of a variety of derived problems.

I then often find myself trying to trick the compiler, wrapping said line in a conditional that I know is true, but the compiler doesn't, for example

    if (target === "bar") {
      throw new Error("foo");
    }

That would then compile and serve my quick testing needs.

I have used this technique so often now that it is starting to bug me. Such a weird paradigm.

Is there a way to explicitly throw an error and have the compiler not be smart about reachability?

I suspect that the answer is "no" in the sense that one cannot have the best of all worlds; but as I am still quite new to this ecosystem I'd love to see what your perspectives are on this.

1 Answers
Related