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.