10LOC

#assertion-functions

TypeScriptintermediate

Assertion functions (asserts x is T) for runtime-checked narrowing

export function assertIsString(value: unknown, name: string): asserts value is string {
  if (typeof value !== "string") {
    throw new TypeError(`${name} must be a string, got ${typeof value}`);
  }
}

Narrow a value by throwing instead of branching, so the rest of the function can assume the checked type without an extra if.