#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 48 of 48hard

What are Assertion Functions?

Functions that assert types.

What You'll Learn

  • Assertion function syntax
  • asserts keyword
  • Practical examples

Assertion Functions

Functions that throw if a condition isn't met, narrowing the type afterward.

code.tsTypeScript
function assert(condition: unknown, msg?: string): asserts condition {
  if (!condition) {
    throw new Error(msg ?? "Assertion failed");
  }
}

function process(value: string | null) {
  assert(value !== null, "Value required");
  // value is now string
  console.log(value.toUpperCase());
}

Type Assertion

code.tsTypeScript
function assertIsString(value: unknown): asserts value is string {
  if (typeof value !== "string") {
    throw new Error("Expected string");
  }
}

function process(value: unknown) {
  assertIsString(value);
  // value is now string
  console.log(value.toUpperCase());
}

Practical Examples

code.tsTypeScript
function assertDefined<T>(
  value: T | undefined | null,
  name: string
): asserts value is T {
  if (value === undefined || value === null) {
    throw new Error(`${name} must be defined`);
  }
}

interface User {
  id: string;
  name: string;
}

function assertIsUser(obj: unknown): asserts obj is User {
  if (!obj || typeof obj !== "object") {
    throw new Error("Expected object");
  }
  if (!("id" in obj) || !("name" in obj)) {
    throw new Error("Missing required fields");
  }
}