Challenge 3: Write an Assertion Function — Possible Solution ==================================================================== function assertIsRecord(value: unknown): asserts value is Record { if (typeof value !== "object" || value === null || Array.isArray(value)) { throw new Error("Expected a plain object"); } } // --- Usage: avoiding repeated checks on every property access --- function processPayload(payload: unknown): void { assertIsRecord(payload); // From this line on, `payload` is narrowed to Record // for the REST of the function — no `if` block, no repeated guards. const name = payload.name; // ✅ compiles — payload is a Record const email = payload.email; // ✅ compiles console.log(`Processing ${String(name)} <${String(email)}>`); } processPayload({ name: "Jane", email: "jane@example.com" }); // logs normally // processPayload("not an object"); // -> throws "Expected a plain object" immediately, before any property access // Compare to the equivalent WITHOUT an assertion function — every function // that needs this check has to repeat the `if` wrapper: function processPayloadWithoutAssert(payload: unknown): void { if (typeof payload !== "object" || payload === null || Array.isArray(payload)) { throw new Error("Expected a plain object"); } // payload narrowed only inside this function, and only because this // particular `if` check happens to exist here — if ten other functions // need the same guard, this whole block gets copy-pasted ten times. const name = (payload as Record).name; } WHY THIS WORKS -------------- - `asserts value is Record` tells the compiler: "if this function returns normally (doesn't throw), treat `value` as Record for every line of code that runs after this call" — narrowing that persists across the rest of the function body, not just inside an `if` block. - The runtime check inside assertIsRecord is what actually backs that promise — it explicitly excludes `null` and arrays (which JavaScript's `typeof` reports as `"object"` too), so the assertion only succeeds for genuine plain objects. - Because the assertion function is reusable, ten different functions needing the same "is this a record" check can all call `assertIsRecord(value)` once at the top, instead of each repeating its own `if (typeof value !== "object" || ...)` block — exactly the "guards at scale" theme of this chapter.