SOLUTION: Challenge 1 - Union & Type Guard ========================================== Challenge: Write a function that accepts either a User object or a user id (number). Inside, use a type guard to determine which was passed and handle each case differently. --- SOLUTION: interface User { id: number; name: string; email: string; } type UserInput = User | number; function getUser(input: UserInput): void { // Type guard using typeof if (typeof input === "number") { console.log(`Fetching user with ID: ${input}`); // Here you'd typically fetch from a database } else { // TypeScript now knows input is a User object console.log(`User: ${input.name} (${input.email})`); } } // Test cases const userId = 42; getUser(userId); // Output: Fetching user with ID: 42 const user: User = { id: 1, name: "Alice", email: "alice@example.com" }; getUser(user); // Output: User: Alice (alice@example.com) --- EXPLANATION: 1. We define a union type UserInput that can be either User or number. 2. Inside getUser(), we use typeof input === "number" to narrow the type: - If true, input is definitely a number (the id) - If false, input must be a User object (TypeScript eliminates the number possibility) 3. This is a type guard — it tells TypeScript "after this check, the type is narrowed." 4. Each branch can now safely access type-specific properties or methods. WHY THIS WORKS: The typeof operator works for primitives (string, number, boolean, undefined). For object types, you'd use instanceof or custom type guards with "value is Type".