logoalt Hacker News

whilenot-devtoday at 1:59 PM1 replyview on HN

  default: {
    const _exhaustive: never = result;
    return _exhaustive;
  }
...is not how people should implement an exhaustiveness check ever! An exhaustiveness check exhausts your knowledge about the world, it should throw an exception at runtime. Just returning the non-matched case is a recipe for disaster. Do this instead:

  default:
    ((value: never) => { throw new Error(`Missing case for value: ${value}`); })(result);

Replies

terminatornet3today at 2:55 PM

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...

show 1 reply