TypeScript · Middle · Question 19 of 75

What is an assertion function?

function assertIsString(x: unknown): asserts x is string {
  if (typeof x !== 'string') throw new Error('Not a string');
}

Explanation

After assertIsString(value), value is a string for the rest of the code, with no if. If the check fails, the function throws. Unlike a type guard (x is T), you don't need to wrap the result in a condition.

Further reading

Problem with a question

TypeScript · Middle · question 19

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz