Skip to the solution
MediumFrontend9 min read

What are assertion functions (asserts)?

1.1k views

The problem

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's assert) and asserts 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 T returning a boolean, narrowing only inside the if)
  • 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 T for class state, test helpers

Code / implementation expected: Yes β€” an assertIsString or assertDefined helper and a call site that is narrowed afterwards.

  • asserts

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptThe two assertion forms, assertDefined and asserts this
TypeScriptPitfalls: TS2775, unchecked bodies and a config validator

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 18 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are union and intersection types?

Continue