Assertion functions có return type asserts condition hoặc asserts param is Type.
Khi function return (không throw), TS assume assertion đúng và narrow type trong phần code tiếp theo.
typescript
function assert(cond: unknown, msg = 'assertion failed'): asserts cond {
if (!cond) throw new Error(msg);
}
function assertIsString(val: unknown): asserts val is string {
if (typeof val !== 'string') throw new TypeError();
}
const val: string | undefined = getValue();
assert(val !== undefined, 'val must exist');
val.toUpperCase(); // OK — TS biết val là string (không còn undefined)