Funciones Tipadas
TypeScript permite tipar parámetros, valores de retorno e incluso el tipo de la función en sí. Esto hace tu código más seguro y mejor documentado.
Tipando Parámetros
typescript
function saludo(nombre: string): void { console.log(`¡Hola, ${nombre}!`);} saludo("Pedro"); // OKsaludo(42); // Error: Argument of type 'number'...Tipando Valores de Retorno
typescript
function suma(a: number, b: number): number { return a + b;} function esPar(n: number): boolean { return n % 2 === 0;} // TypeScript infiere, pero ser explícito es una buena prácticafunction multiplicar(a: number, b: number) { return a * b; // tipo de retorno inferido como number}Parámetros Opcionales
Usa ? para parámetros opcionales (deben ir al final):
typescript
function crearUsuario( nombre: string, email: string, edad?: number): object { return { nombre, email, edad };} crearUsuario("Pedro", "pedro@email.com"); // OKcrearUsuario("Pedro", "pedro@email.com", 30); // OKValores por Defecto
typescript
function potencia(base: number, exponente: number = 2): number { return Math.pow(base, exponente);} potencia(5); // 25 (5²)potencia(5, 3); // 125 (5³)Rest Parameters
Para aceptar un número variable de argumentos:
typescript
function sumarTodos(...numeros: number[]): number { return numeros.reduce((acc, n) => acc + n, 0);} sumarTodos(1, 2, 3); // 6sumarTodos(1, 2, 3, 4, 5); // 15Arrow Functions Tipadas
typescript
// En líneaconst doblar = (n: number): number => n * 2; // Con tipo de función separadotype Operacion = (a: number, b: number) => number; const suma: Operacion = (a, b) => a + b;const restar: Operacion = (a, b) => a - b;Sobrecarga de Funciones
Define múltiples firmas para una función:
typescript
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("hello"); // "HELLO"formatear(3.14159); // "3.14"Funciones como Parámetros
Pasa funciones como argumentos con tipado:
typescript
function ejecutar( callback: (mensaje: string) => void): void { callback("¡Operación completada!");} ejecutar((msg) => console.log(msg)); // O con un tipo nombradotype Callback = (mensaje: string) => void; function ejecutarConTipo(callback: Callback): void { callback("