Volver a Fundamentos
Ir al examen del modulo
Fundamentos — Leccion 10
·15 minType Inference
Cómo TypeScript adivina los tipos automáticamente.
Type Inference
TypeScript puede adivinar el tipo sin que lo declares. Esto se llama inferencia de tipos.
typescript
// TypeScript infiere: string
let nombre = "Ana";
// TypeScript infiere: number
let edad = 25;
// TypeScript infiere: boolean
let activo = true;
// TypeScript infiere: number[]
let numeros = [1, 2, 3];
Inferencia en funciones
typescript
// TypeScript infiere el tipo de retorno
function sumar(a: number, b: number) {
return a + b; // Retorno inferido: number
}
// TypeScript infiere parámetros
function saludar(nombre) {
// Error: Parameter 'nombre' implicitly has an 'any' type
}
Inferencia en arrays
typescript
// Infiere: number[]
let nums = [1, 2, 3];
// Para array mixto, se necesita Union type
let mixto = [1, "dos"]; // (string | number)[]
Inferencia en objetos
typescript
// TypeScript infiere la forma completa
let persona = {
nombre: "Ana",
edad: 25,
activo: true,
};
// Persona tiene tipo:
// { nombre: string; edad: number; activo: boolean }
Cuando NO inferir
typescript
// Mejor ser explicito en:
// 1. Variables vacías
let resultado: string;
// 2. Parámetros de función
function procesar(dato: string) { }
// 3. Retorno de funciones complejas
function fetchData(): Promise<string[]> { }
// 4. Estado de componentes
let estado: "cargando" | "exito" | "error";
as const
Para inferir tipos literales en vez de tipos amplios.
typescript
// Sin as const: tipo es string
let color = "rojo";
// Con as const: tipo es "rojo"
const colorLiteral = "rojo" as const;
// Array cómo tuple
let punto = [10, 20] as const; // readonly [10, 20]
Ejercicio pratico
Sin usar tipos explícitos, deja que TypeScript infiere los tipos. Luego verifica con typeof.
exercise.ts
Loading...
Resultado
Haz clic en "Ejecutar" para ver el resultado...