Volver al curso

TypeScript Completo

leccion
5 / 13
beginner
10 horas
Modelado real (unions, interfaces, generics)

Unions + narrowing: manejar estados sin bugs

Lectura
18 min~1 min lectura

Unions y narrowing

Aprende a modelar estados (loading/success/error) con unions y a usar narrowing para que el compilador te ayude.

Conceptos clave

  • Discriminated unions
  • Type guards (in, typeof, custom)
  • Exhaustive checks

Ejemplo

type Result<T> =
  | { ok: true; data: T }
  | { ok: false; error: string };

function parseId(input: string): Result<string> {
  if (!input.startsWith('u_')) return { ok: false, error: 'invalid id' };
  return { ok: true, data: input };
}

const r = parseId('u_123');
if (!r.ok) {
  console.error(r.error);
} else {
  console.log(r.data);
}

Ejercicio

  • Crea un union para estados de un request: idle/loading/success/error.
  • Usa exhaustive check para garantizar que cubriste todos.

Checklist de mastery

  • Puedo evitar null checks infinitos con unions.
  • Se escribir type guards simples.