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');
}- ✓Correct answer: A function after whose successful call TS treats the argument's type as narrowed
- 2A function that returns
trueorfalseto check a type - 3A function that works only in tests
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.