Lección 7 de 13 · Lectura y práctica
Generics en la practica (lo justo)
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.
Esta es una lección del contenido anterior de Cursalo. Si ya estudiaste o compraste este curso, entra con tu cuenta para guardar tu progreso y abrir el resto de las clases. No necesitas comprar nada de nuevo.
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.