CodeBlanks Logo Icon CodeBlanks

asserts is

Learn the asserts x is T syntax.

asserts is

The asserts x is T return type specifies the signature of an assertion function. The function body must throw if the condition fails; on normal completion TypeScript narrows the parameter x to T. No if condition is needed; in the lines after the call x is treated as T.

function assertString(x: unknown): asserts x is string {
  if (typeof x !== "string") {
    throw new Error("not a string");
  }
}

function process(v: unknown): string {
  assertString(v);
  return v.toUpperCase();  // v: string
}

Narrowing after the call

After calling assertString(v), in subsequent lines v is narrowed to string. No if condition is needed; this makes the code flow more naturally than with a type guard. The throw mechanism explicitly stops execution on error.

function assertNumber(x: unknown): asserts x is number {
  if (typeof x !== "number") throw new Error("not a number");
}

function double(v: unknown): number {
  assertNumber(v);
  return v * 2;  // v: number, no if needed
}

Practice Handle unknown with assertNumber

Define an assertNumber(x: unknown): asserts x is number function (with throw new Error("not a number") when typeof x !== "number"). Write a double(v: unknown): number function: call assertNumber(v), then return v * 2. Print the result via console.log(double(21)).

Starter code

index.ts
// assertNumber fonksiyonunu tanımla (asserts x is number, throw ile)

// double(v: unknown): number fonksiyonunu assertNumber ile yaz

// double(21) sonucunu yazdır

Sample solution

index.ts
function assertNumber(x: unknown): asserts x is number {
  if (typeof x !== "number") {
    throw new Error("not a number");
  }
}

function double(v: unknown): number {
  assertNumber(v);
  return v * 2;
}

console.log(double(21));

Expected output

42

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What should the body of a function with the asserts x is T signature do?

  • Return the T value
  • Call console.log
  • Throw if the condition fails Correct answer
  • Return true/false

Explanation: A function with the asserts x is T signature must throw if the condition fails; on normal completion TypeScript narrows x to T. No return is needed.

2 asserts keyword

Question
function assertString(x: unknown): ____ x is string {
  if (typeof x !== "string") throw new Error("not string");
}
Answer
function assertString(x: unknown): asserts x is string {
  if (typeof x !== "string") throw new Error("not string");
}

Explanation: The asserts keyword indicates that the return type is an assertion function; it narrows on completion and expects the body to throw on failure.

3 asserts is parts

Term Meaning
asserts x is T assertion signature
throw yapma in body when condition fails
çağrı sonrası daraltma no if needed
assertString(v) next line: v is string

All lessons in Advanced