Question presented to candidate:
"What is an assertion function in TypeScript β the asserts keyword in a return type? How is it different from a type guard that returns value is T, and what can go wrong with it?"
What a strong answer should cover:
- The two forms:
asserts condition(like Node'sassert) andasserts value is T; added in TypeScript 3.7 - Behaviour: if the function returns, the compiler narrows for the rest of the scope; if the check fails, the function throws
- The difference from a type guard (
value is Treturning a boolean, narrowing only inside theif) - Rules: the function must return
void, and every name in the call target needs an explicit type (TS2775), which trips up arrow functions and methods on inferred instances - The compiler trusts the signature, not the body: a wrong or empty check is an unchecked lie, so keep assertion bodies small and tested
- Uses: validating inputs and config at boundaries,
assertDefined,asserts this is Tfor class state, test helpers
Code / implementation expected: Yes β an assertIsString or assertDefined helper and a call site that is narrowed afterwards.