capypad
0 day streak
typescript / expert
Snippet

Assertion Signatures for Runtime Guarding

Assertion signatures use the 'asserts' keyword to tell the compiler that if a function returns normally, a certain condition must be true. This narrows types across the remainder of the containing scope, reducing the need for nested if-blocks.

snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
function assertIsString(val: any): asserts val is string {
if (typeof val !== "string") {
throw new Error("Not a string!");
}
}
 
function process(input: unknown) {
assertIsString(input);
// input is now narrowed to 'string' for the rest of the scope
console.log(input.toUpperCase());
}
Breakdown
1
asserts val is string
The signature indicating that the function narrows the 'val' parameter upon successful execution.
2
input.toUpperCase()
Allowed because the compiler knows 'input' must be a string after the assertion call.