S
Seoffix.com
Sign In Get Pro Membership

JavaScript & TypeScript

TypeScript: Discriminated Unions for Type-Safe API Gateways

Intermediate TypeScript 25 XP

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'.

Hints

  1. Use a switch (res.status) block
  2. Inside case 'success': res.data is guaranteed to exist
  3. Inside case 'error': res.message is guaranteed to exist

Your answer

This lesson is checked against the lesson rules. Your code is never run on our servers.

AI Code Explainer & Translator

Runs without any outside service.
 
Mark Complete & Earn XP
Earn 25 XP. Finish every lesson in the track to earn its certificate.
Sign in to earn XP