assertNever

import { assertNever } from "jsr:@ende/assert/unstable-never";

function ยท experimental

function assertNever(x: never, msg?: string): never

Make an assertion that x is of type never. If not then throw.

x: never

The value to be checked as never

msg?: string

The optional message to display if the assertion fails.

Returns

Never returns, always throws.

Example: Exhaustivenss check

import { assertNever } from "@ende/assert/unstable-never";

type Kinds = "A" | "B";

function handleKind(kind: Kinds) {
  switch (kind) {
    case "A":
      doA();
      break;
    case "B":
      doB();
      break;
    default:
      assertNever(kind);
  }
}

function doA() {
  // ...
}

function doB() {
  // ...
}

Example: Compile-time error when there is a missing case

import { assertNever } from "@ende/assert/unstable-never";

type Kinds = "A" | "B" | "C";

function handleKind(kind: Kinds) {
  switch (kind) {
    case "A":
      doA();
      break;
    case "B":
      doB();
      break;
    default:
      // Type error since "C" is not handled
      assertNever(kind);
  }
}

function doA() {
  // ...
}

function doB() {
  // ...
}

Source