Tutorial
TypeScript Pro Tips: 10 técnicas para subir de nivel tu frontend
Domina utility, conditional y template literal types; patrones con infer y uniones discriminadas. Guía práctica.
agosto de 2025
9 min de lectura
TypeScriptPatronesDXBest PracticesFrontend
TypeScript Pro Tips: 10 técnicas clave
TL;DR
Apóyate en Utility/Conditional/Template Literal Types, uniones discriminadas y tipos "brandeados". Tip: añade tests de tipos con tsd
o expectTypeOf
.
1. Utility Types bien usados
type PublicUser = Omit<User, 'password'>
type UserUpdate = Partial<Pick<User, 'name'|'email'>>
2. Template Literal Types
type ButtonClass = `btn-${'light'|'dark'}-${'sm'|'md'|'lg'}`
3. Conditional Types
type ApiResponse<T> = T extends string ? { message: T } : T extends number ? { count: T } : { data: T }
4. Branded Types
type UserId = string & { readonly brand: unique symbol }
5. Discriminated Unions
type AsyncState = { status: 'loading' } | { status: 'success'; data: User[] } | { status: 'error'; error: string }
6. Genéricos con constraints
function updateEntity<T extends {id:string}>(entity: T, updates: Partial<Omit<T,'id'>>): T {
return { ...entity, ...updates }
}
7. Mapped Types
type Nullable<T> = { [K in keyof T]: T[K] | null }
8. Index Signatures
interface FormErrors { [field: string]: string|undefined }
9. Function Overloads
function createElement(tag: 'button'): HTMLButtonElement
function createElement(tag: string): HTMLElement { return document.createElement(tag) }
10. Patrones con infer
type GetArrayType<T> = T extends (infer U)[] ? U : never
Bonus: tests de tipos
// vitest + expectTypeOf
import { expectTypeOf } from 'vitest'
expectTypeOf<PublicUser>().toMatchTypeOf<{ id:string; name:string; email:string }>()
Conclusión
Empieza por Utility/Discriminadas y añade branded/conditional según complejidad. Mantén los tipos legibles y cubre invariantes con tests de tipos.