Modern TypeScript Patterns
TypeScript continues to evolve, and with it come new patterns that make our code safer and more expressive. Here are the patterns we use most at Ruzora across our FastAPI integrations and Next.js frontends.
Discriminated Unions
Discriminated unions are one of the most powerful patterns in TypeScript. They allow you to model complex state machines with compile-time safety.
type Result<T> =
| { status: 'success'; data: T }
| { status: 'error'; error: string }
| { status: 'loading' }The compiler narrows the type based on the status field, giving you autocomplete and type checking at every branch.
Branded Types
Branded types prevent mixing up primitive values that represent different things. At Ruzora, we use them to distinguish user IDs from candidate IDs from payment IDs.
type UserId = string & { __brand: 'UserId' }
type CandidateId = string & { __brand: 'CandidateId' }Zero runtime cost, full compile-time safety.
Template Literal Types
Template literal types let you create string types that follow specific patterns — perfect for API routes, event names, and configuration keys.
type APIRoute = `/api/${string}`
type EventName = `on${Capitalize<string>}`Key Vocabulary
/ Vocabulario ClaveWhen code is being converted to machine code, before running
“TypeScript catches errors at compile-time.”
Preventing operations on incompatible data types
“Branded types provide compile-time type safety.”
A type where a shared field determines the variant
“Use a discriminated union to model API responses.”
When the program is actually executing
“Branded types have zero runtime cost.”
Reducing a type to a more specific one through checks
“The compiler narrows the type based on the status field.”
Comprehension Check
/ Verificación de Comprensión1. What is a 'discriminated union'?
2. What does 'zero runtime cost' mean?
3. What is 'type narrowing'?
4. What are branded types useful for?
