Volver a TypeScript Básico

Funciones y Genéricos

TypeScript añade seguridad de tipos a las firmas de funciones e introduce genéricos para código reutilizable y seguro.

Firmas de Función Tipadas

// Parámetros y tipo de retorno function sumar(a: number, b: number): number { return a + b; } // Función flecha con tipos const multiplicar = (a: number, b: number): number => a * b; // Retorno void function registrarMensaje(mensaje: string): void { console.log(mensaje); } // Never — la función nunca retorna (lanza error o bucle infinito) function fallar(mensaje: string): never { throw new Error(mensaje); }

Parámetros Opcionales y por Defecto

function crearUsuario( nombre: string, rol: string = "visitante", edad?: number // opcional ): { nombre: string; rol: string; edad?: number } { return { nombre, rol, edad }; } crearUsuario("Alice"); crearUsuario("Bob", "admin", 30);

Sobrecargas de Función

function formatear(valor: string): string; function formatear(valor: number): string; function formatear(valor: string | number): string { if (typeof valor === "string") return valor.toUpperCase(); return valor.toFixed(2); } formatear("hola"); // "HOLA" formatear(3.14159); // "3.14"

Genéricos — Lo Básico

// Sin genéricos — pierde información de tipo function primerElemento(arr: any[]): any { return arr[0]; } // Con genéricos — preserva el tipo function primerElemento<T>(arr: T[]): T | undefined { return arr[0]; } const num = primerElemento([1, 2, 3]); // tipo: number const str = primerElemento(["a", "b"]); // tipo: string

Restricciones Genéricas

// T debe tener una propiedad 'length' function elMasLargo<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b; } elMasLargo("hola", "hi"); // "hola" elMasLargo([1, 2, 3], [4, 5]); // [1, 2, 3]

Interfaces y Tipos Genéricos

interface RespuestaApi<T> { datos: T; estado: number; mensaje: string; } interface Paginado<T> { items: T[]; total: number; pagina: number; porPagina: number; } // Uso type RespuestaUsuarios = RespuestaApi<Usuario[]>; type PaginaUsuarios = Paginado<Usuario>; async function obtenerUsuarios(): Promise<RespuestaUsuarios> { const res = await fetch("/api/usuarios"); return res.json(); }

Funciones Utilitarias Genéricas

// Patrón repositorio genérico class Repositorio<T extends { id: number }> { private items: T[] = []; agregar(item: T): void { this.items.push(item); } buscarPorId(id: number): T | undefined { return this.items.find(item => item.id === id); } obtenerTodos(): T[] { return [...this.items]; } } const repoUsuarios = new Repositorio<Usuario>(); repoUsuarios.agregar({ id: 1, nombre: "Alice", correo: "[email protected]", rol: "usuario" });

Consejo genérico: Nombra los parámetros genéricos significativamente — T para tipos generales, K/V para clave/valor, E para elementos, R para tipos de retorno.