index.ts 906 B

12345678910111213141516171819202122232425262728293031323334353637
  1. /**
  2. * Helper function for exhaustive checks of discriminated unions.
  3. * https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html
  4. *
  5. * @example
  6. *
  7. * type A = {type: 'a'};
  8. * type B = {type: 'b'};
  9. * type Union = A | B;
  10. *
  11. * function doSomething(arg: Union) {
  12. * if (arg.type === 'a') {
  13. * return something;
  14. * }
  15. *
  16. * if (arg.type === 'b') {
  17. * return somethingElse;
  18. * }
  19. *
  20. * // TS will error if there are other types in the union
  21. * // Will throw an Error when called at runtime.
  22. * // Use `assertNever(arg, true)` instead to fail silently.
  23. * return assertNever(arg);
  24. * }
  25. */
  26. export function assertNever(value: never, noThrow?: boolean): never {
  27. if (noThrow) {
  28. return value
  29. }
  30. throw new Error(
  31. `Unhandled discriminated union member: ${JSON.stringify(value)}`,
  32. );
  33. }
  34. export default assertNever;