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");
}- Expected result: The program prints HELLO, then Expected text.
- After assertText returns, value is narrowed to string.
- 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