What is an assertion function in TypeScript?
An assertion function has a return type like asserts x is string. If it returns normally, TypeScript narrows x for the rest of the scope; if the check fails it must throw. It works like a guard that replaces an if block.
Explain it simply
A type guard is a question: "is this a string?" and you branch on the answer. An assertion function is a bouncer: if you got past him, you must be of age. If not, he throws you out (throws an error), so the code after him can assume the fact.
This suits validation at the top of a function: check once, and every line below sees the narrowed type, with no nested if.
Example
function assertIsString(x: unknown): asserts x is string {
if (typeof x !== "string") {
throw new Error("Expected a string");
}
}
function shout(value: unknown) {
assertIsString(value);
return value.toUpperCase(); // value: string from here on
}
// Condition form, similar to Node's assert()
function assert(cond: unknown, msg: string): asserts cond {
if (!cond) throw new Error(msg);
}
function area(w: number | undefined) {
assert(w !== undefined, "width missing");
return w * 2; // w: number
}What to say in the interview
"An asserts function narrows the argument after the call returns, and throws if the condition fails. I use it for validation at the start of a function so the rest of the body works with the narrowed type without extra nesting. The function must be declared with an explicit type annotation to be recognised."
Common mistakes
- Forgetting to throw on failure; the compiler trusts the signature, not the body.