TypeScript Today I Learned

I recently added this helper function to my TypeScript codebase:

export function assertNever(value: never): never {
  throw Error(`Unexpected value '${value}'`);
}

What it does is helps you implement exhaustive logic branches. Its use is ideal in switch statements.

Consider the following:

type Color = "red" | "blue" | "orange";

const renderColor = (color: Color) => {
  switch (color) {
    case "red": {
      return "#E83913";
    }
    case "blue": {
      return "#1371E8";
    }
    default: {
      assertNever(color);    }
  }
};

This will actually give you a compiler error in the default case, because you forgot to add a case for 'orange'.

Whenever I build exhaustive logic statements like this, I start with the assertNever default case and then I use it as a guide to make sure I have every case handled.

Here is the section of the TypeScript docs that I got this from.

TIL how easy it is to do exhaustive case-checking in TypeScript!