Skip to main content
InterviewHubPRO
Section Overview
Q28

Question 28 of 50

Part 2: Advanced Type System & Metaprogramming (Mid-Level)

56%
TypeScript Master (50 Qs)•Part 2: Advanced Type System & Metaprogramming (Mid-Level)

What is the `asserts` condition operator?

junior LevelCode ExampletypescriptAdvanced Type System

In Simple Words: The asserts keyword defines an assertion function. If the function returns without throwing, TypeScript narrows the type of the argument for all subsequent lines in that scope:

typescript
function assertIsString(val: any): asserts val is string {
  if (typeof val !== "string") {
    throw new Error("Not a string!");
  }
}

function processValue(x: unknown) {
  assertIsString(x);
  console.log(x.toUpperCase()); // Safe! TS knows x is string from here on
}