logoalt Hacker News

terminatornet3today at 2:55 PM1 replyview on HN

The original author is correct. Their implementation of an exhaustive check will give you a compiler error if you miss a variant in your switch statement. I much prefer a compiler error over a run time error.

It's even recommended in the official typescript docs - https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...


Replies

whilenot-devtoday at 3:47 PM

> Their implementation of an exhaustive check will give you a compiler error if you miss a variant in your switch statement. I much prefer a compiler error over a run time error.

What are you talking about? You'd still get the compile error just the same.

Falling back on returning the input argument doesn't even make sense in the typescript docs:

  type Shape = Circle | Square;
 
  function getArea(shape: Shape) {
    switch (shape.kind) {
      case "circle":
        return Math.PI * shape.radius ** 2;
      case "square":
        return shape.sideLength ** 2;
      default:
        const _exhaustiveCheck: never = shape;
        return _exhaustiveCheck;
    }
  }
Case circle and square are returning a number, but an unknown shape is returning itself? This is especially annoying when teammates are starting to cast values into a Shape throughout the codebase. Guess I'll need to make a PR to the typescript docs.
show 1 reply