Course contentsShow
← TypeScript
Lesson 231 of 1,7965. Type Narrowing FundamentalsFree lesson

Type Assertion Function Syntax

Using `asserts param is Type` to both validate and narrow a parameter's type after the call.

What You'll Learn

You'll learn how to write assertion functions that use the asserts param is Type syntax to both validate and narrow a parameter's type for all code that follows.


The Core Idea

In the previous lesson, you saw assertion functions that throw errors if a condition fails, but didn't change TypeScript's understanding of types. Now you'll use asserts param is Type syntax to tell TypeScript: "If this function returns normally, the parameter is definitely this specific type."

Think of it like a security checkpoint with a type scanner. A regular assertion function just checks if you should pass through. But asserts param is Type also stamps your passport with the verified type, so everyone downstream knows exactly what you are.


The Syntax

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

let mystery: unknown = 'hello';

assertIsString(mystery);
// After this point, TypeScript knows mystery is string
console.log(mystery.toUpperCase()); // ✓ Safe!

Notice the return type: asserts value is string. This tells TypeScript two things:

  1. This function throws if value isn't a string
  2. If it returns, value is a string

Why This Matters

You're combining runtime validation with compile-time type narrowing. The function both checks the type and teaches TypeScript what you've proven.

function processValue(input: string | number) {
  assertIsString(input);
  // input is now string only
  return input.length;
}

Key Takeaway: Use asserts param is Type syntax to write assertion functions that both validate at runtime and narrow the type for all subsequent code, giving you safety and clarity in one step.