ReviseAlgo Logo

Error Handling & Patterns

Assertion Functions

Perform runtime checks and narrow variable types using asserts condition syntax.

Last Updated: July 29, 2026 10 min read

Assertion functions perform runtime checks that throw an error if a condition is false, while informing TypeScript compiler that the condition is guaranteed true for the remainder of the block.

1. Introduction & Architecture

2. Deep Dive & Core Concepts

An assertion signature uses the asserts condition return type syntax.

3. Basic Code Example

4. Advanced Production Patterns

5. Interactive Code Playground

function assertString(val: unknown): asserts val is string {
  if (typeof val !== 'string') throw new Error("Not a string");
}

const input: unknown = "Hello World"; assertString(input); console.log(input.length);

6. Common Pitfalls & Edge Cases

Warning: Assertion functions must be plain function declarations or arrow functions with explicit return type annotations (: asserts val is T).

7. Interview Q&A & Quizzes

Q: What is the difference between Type Predicates and Assertion Functions?

A: Type predicates return a boolean (val is T) for if-conditions; assertion functions throw on failure and narrow the current scope (asserts val is T).

8. Summary Comparison Table

Function TypeSyntaxControl Flow
Type Predicatefn(): val is TUsed in if (fn(x)) branches
| Assertion Function | fn(): asserts val is T | Throws on failure, narrows remaining scope |