Codectionary / Developer documentation / TypeScript

Runtime Checks with Assertion Functions

An assertion function states that normal return guarantees a condition or narrower type. It should throw when the assertion is false. TypeScript 3.7 added assertion signatures; unlike an as assertion, this pattern includes executable validation.

Syntax

function assertText(value: unknown): asserts value is string { /* throw if invalid */ }

Examples

Runtime Checks with Assertion Functions: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints HELLO, then Expected text.

function assertText(value: unknown): asserts value is string {
  if (typeof value !== "string") throw new TypeError("Expected text");
}
function shout(value: unknown): string {
  assertText(value);
  return value.toUpperCase();
}
console.log(shout("hello"));
try { shout(42); } catch (error) {
  console.log(error instanceof Error ? error.message : "Unknown failure");
}
  1. Expected result: The program prints HELLO, then Expected text.
  2. After assertText returns, value is narrowed to string.
  3. The invalid number triggers an actual exception rather than being converted to text.

Best practices

  • Use assertion functions for invariants that should stop execution on failure.
  • Use boolean guards when failure is an ordinary branch the caller should handle.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading