Assertion functions & user-defined type guards
Write assertion functions (asserts x is T) and user-defined type guards (x is T) to narrow unknown/union values safely.
Intro
Goal: Turn runtime checks into type refinements with assertion functions and user-defined type guards for safe APIs.
Assertion function
An assertion function narrows types for subsequent code if it returns; otherwise, it must throw.
function assertIsString(x: unknown): asserts x is string {
if (typeof x !== "string") {
throw new Error("Expected string");
}
}
let v: unknown = Math.random() > 0.5 ? "ok" : 42;
assertIsString(v); // after this, v is string
console.log(v.toUpperCase());All lessons in this course
- Function overloads & call signatures
- this parameter typing; void, never
- Assertion functions & user-defined type guards