Use this file to discover all available pages before exploring further.
Este módulo ofrece una serie de ejercicios estructurados en 5 carpetas temáticas que cubren TypeScript de forma progresiva, desde los tipos primitivos hasta los generics avanzados y utility types. Cada archivo es un ejercicio independiente con comentarios explicativos integrados en el código.
// 01-primitivos.ts// TypeScript infiere el tipo según el contexto del tokenconst ciudad = "Madrid" // tipo literal: "Madrid"let pais = "España" // tipo inferido: string (puede reasignarse)// Tipos numéricoslet color = 0x09f // hexadecimal → numberlet infinito = Infinity // también number// Tipos especialesconst numeroGrande: bigint = 9007199254741991nconst id: symbol = Symbol("id")let age: number | null = null // union type con null
// 05-any-unknown-never-void.ts// any: desactiva TypeScript completamente — EVITARlet cualquierCosa: any = "hola"cualquierCosa = 42const result = cualquierCosa + 8 // sin error, sin seguridad// unknown: acepta cualquier valor pero exige verificación antes de usarlet valorDesconocido: unknown = "hola"if (typeof valorDesconocido === 'number') { const resultadoSeguro = valorDesconocido + 8 // ✅ seguro}// void: funciones que no retornan un valor útilfunction saludar(): void { console.log("Hola!")}// never: funciones que nunca terminan o siempre lanzan errorfunction throwErrror(message: string): never { throw new Error(message)}
El type narrowing permite a TypeScript reducir un tipo amplio a uno específico mediante comprobaciones en tiempo de ejecución:
typeof
in operator
instanceof
function procesar(valor: number | string) { if (typeof valor === 'number') { // TypeScript sabe que valor es number aquí console.log(valor.toFixed(2)) } else { // TypeScript sabe que valor es string aquí console.log(valor.toUpperCase()) }}
type Pez = { nadar: () => void; nombre: string }type Pajaro = { volar: () => void; nombre: string }type Perro = { ladrar: () => void; nombre: string }type Animal = Pez | Pajaro | Perrofunction moverAnimal(animal: Animal) { if ('nadar' in animal) { animal.nadar() // TypeScript sabe que es Pez } else if ('volar' in animal) { animal.volar() // TypeScript sabe que es Pajaro } else { animal.ladrar() // TypeScript sabe que es Perro }}
function formatDate(value: Date | string): string { if (value instanceof Date) { return value.toUTCString() // TypeScript sabe que es Date } return new Date(value).toUTCString() // TypeScript sabe que es string}
// Función genérica: T es el parámetro de tipofunction identity<T>(value: T): T { return value}identity<string>("hola") // T = stringidentity<number>(42) // T = numberidentity("inferido") // T inferido como string automáticamente// Genérico con constraint: T debe tener la propiedad lengthfunction getLength<T extends { length: number }>(item: T): number { return item.length}getLength("hola") // ✅ string tiene lengthgetLength([1, 2, 3]) // ✅ array tiene lengthgetLength({ length: 10 }) // ✅ objeto con length// Múltiples parámetros de tipofunction pair<T, U>(first: T, second: U): [T, U] { return [first, second]}const result = pair("nombre", 42) // [string, number]
# Ejecutar un archivo TypeScript directamentenpx tsx 06-typescript/01-fundamentos/00-types.tsnpx tsx 06-typescript/02-funciones/02-type-narrowing.ts
2
Compilar con tsc
# Compilar y ejecutarnpx tsc --strict 06-typescript/01-fundamentos/01-primitivos.tsnode 06-typescript/01-fundamentos/01-primitivos.js
3
Verificar tipos sin compilar
# Solo chequeo de tipos, sin generar archivos JSnpx tsc --strict --noEmit 06-typescript/04-generics/01-generics-basicos.ts
La carpeta 06-typescript/ no tiene package.json propio. Para ejecutar los ejercicios necesitas tener tsx o tsc disponible, ya sea instalado globalmente (npm install -g tsx typescript) o usando npx como en los ejemplos anteriores. Si usas el package.json del módulo 08-sql/backend, ya tienes tsx y typescript como devDependencies y puedes usarlos desde allí.