Robust Error Handling with Discriminated Unions
In traditional JavaScript, API functions often return objects with ambiguous optional fields:{ success: boolean, data?: T, error?: string }
If success is true, developers must still check if data is undefined.
By using a Discriminated Union with a shared literal discriminator (status: 'success' | 'error'), TypeScript automatically narrows types and guarantees data exists when status === 'success'.