API reference@evolu/commonFunction › exhaustiveCheck

function exhaustiveCheck(value: never): never;

Defined in: packages/common/src/Function.ts:89

Helper function to ensure exhaustive matching in a switch statement. Throws an error if an unhandled case is encountered.

Example

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

const handleColor = (color: Color): void => {
  switch (color) {
    case "red":
      console.log("Handling red");
      break;
    case "green":
      console.log("Handling green");
      break;
    case "blue":
      console.log("Handling blue");
      break;
    default:
      exhaustiveCheck(color); // Ensures all cases are handled
  }
};

Use this primarily in side-effect switches (void branches). For value-producing switches, TypeScript can enforce exhaustiveness without a default branch.

Example

Return from each case for value-producing switches.

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

const colorToHex = (color: Color): string => {
  switch (color) {
    case "red":
      return "#ff0000";
    case "green":
      return "#00ff00";
    case "blue":
      return "#0000ff";
  }
};

Example

Use assignment + no default to get exhaustiveness by definite assignment.

type Input =
  | { readonly type: "Mutate" }
  | { readonly type: "Query" }
  | { readonly type: "Export" };

const onInput = (input: Input): void => {
  let result: "A" | "B" | "C";

  switch (input.type) {
    case "Mutate":
      result = "A";
      break;
    case "Query":
      result = "B";
      break;
    case "Export":
      result = "C";
      break;
  }

  handleKind(result);
};

const handleKind = (kind: "A" | "B" | "C"): void => {
  console.log(kind);
};