Q13: What are Assertion Functions using the `asserts` keyword?
Assertion functions throw an error if a condition check fails. They use the return signature asserts condition or asserts val is T to instruct TypeScript that if the function returns normally without throwing, the asserted type assumption holds true for remaining code execution.
Assertion Function Pattern
function assertIsString(val: unknown): asserts val is string {
if (typeof val !== "string") {
throw new Error("Not a string!");
}
}
function processInput(input: unknown) {
assertIsString(input);
// input is now safely narrowed to string for all following lines
console.log(input.toUpperCase());
}💡 If assertIsString completes without throwing an error, TypeScript narrow input to string for the remaining scope.
Key Takeaways
assertsnarrowing stays active across subsequent lines without requiring anifblock.