Interview Q&A / TypeScript

AdvancedQuick answer1 min readUpdated 3 Oct 2026

What is an assertion function in TypeScript?

SHORT ANSWER

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

ts
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.

#narrowing#assertions#functions

Related questions

Practise more TypeScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open TypeScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.