Volver al curso

TypeScript Completo

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

Generics en la practica (lo justo)

Lectura
18 min~1 min lectura

Generics

Generics te permiten reutilizar tipos sin perder seguridad. Aprende 3 patrones que aparecen todo el tiempo.

Conceptos clave

  • Generic functions <T>
  • Constraints: <T extends ...>
  • Generics para colecciones y helpers

Ejemplo

function first<T>(items: T[]): T | null {
  return items.length ? items[0] : null;
}

type WithId = { id: string };
function byId<T extends WithId>(items: T[], id: string): T | null {
  return items.find((i) => i.id === id) ?? null;
}

Ejercicio

  • Escribe un helper groupBy<T>(items, keyFn).
  • Agrega constraint para exigir key string.

Checklist de mastery

  • Se escribir un generic simple sin over-engineering.
  • Se usar extends para constraints.