typescript

Discriminated Unions

Type-safe state handling with tagged union types

Tarun Sharma
Tarun SharmaJanuary 15, 2024 · 1 min read · Last Updated:

API Response States

type ApiState<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: string };

function handleState<T>(state: ApiState<T>) {
  switch (state.status) {
    case 'idle':
      return 'Ready to fetch';
    case 'loading':
      return 'Loading...';
    case 'success':
      return state.data; // TypeScript knows data exists
    case 'error':
      return state.error; // TypeScript knows error exists
  }
}

Redux-style Actions

type Action = { type: 'INCREMENT' } | { type: 'DECREMENT' } | { type: 'SET'; payload: number };

function reducer(state: number, action: Action): number {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    case 'SET':
      return action.payload; // payload is available
  }
}

Form Field Types

type FormField =
  | { type: 'text'; value: string; maxLength?: number }
  | { type: 'number'; value: number; min?: number; max?: number }
  | { type: 'select'; value: string; options: string[] };

function renderField(field: FormField) {
  if (field.type === 'select') {
    return field.options.map((opt) => opt); // options available
  }
}

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub


Tarun Sharma

Written byTarun Sharma
Full-stack developer and tech educator with 10+ years of experience building scalable applications. Passionate about Node.js, NestJS, React, and cloud technologies. Creator of 50+ courses on Udemy and active YouTube educator helping developers level up their skills.
Connect

Is this page helpful?

Related VideosView All

Stack Overflow Clone - APIs Integration Redux Toolkit [Closure] - App Demo #05

Become Ninja Developer - API security Best Practices with Node JS Packages #15

Nest JS Microservices using HTTP Gateway and Redis Services (DEMO) #nestjs #microservices #16