Problem Statement
Write two assertion functions: asserts condition, and asserts value is T; show impact on narrowing.
Explanation
Use `asserts condition` for general checks, and `asserts value is T` to narrow a variable to a specific type. After a successful call, the compiler treats the path as narrowed.
Code Solution
SolutionRead Only
export function assert(cond: unknown, msg = 'Assertion failed'): asserts cond {
if (!cond) throw new Error(msg);
}
export function assertIsString(x: unknown): asserts x is string {
if (typeof x !== 'string') throw new Error('Expected string');
}
// Usage
const v: unknown = Math.random() > 0.5 ? 'hi' : 42;
assertIsString(v); // after this line, v: string
console.log(v.toUpperCase());