Why TypeScript?
TypeScript has become the de-facto standard for large JavaScript projects. Beyond catching bugs at compile time, it serves as living documentation for your codebase.
Discriminated Unions
One of the most powerful TypeScript patterns is discriminated unions — perfect for modeling state machines.
ts
type RequestState<T> =
| { status: class="sh-string">'idle' }
| { status: class="sh-string">'loading' }
| { status: class="sh-string">'success'; data: T }
| { status: class="sh-string">'error'; error: string }
function render(state: RequestState<User>) {
switch(state.status) {
case class="sh-string">'success': return state.data.name class="sh-comment">// fully typed!
case class="sh-string">'error': return state.error
}
}Template Literal Types
Template literal types let you create precise string types.
ts
type EventName = class="sh-string">`on${Capitalize<string>}`
type CSSUnit = class="sh-string">`${number}px` | class="sh-string">`${number}rem` | class="sh-string">`${number}%`Satisfies Operator
The satisfies operator (TS 4.9+) validates a value against a type without widening it.
ts
const palette = {
red: [255, 0, 0],
green: class="sh-string">"#00ff00",
} satisfies Record<string, string | number[]>
class="sh-comment">// palette.red is number[], not string | number[]Conclusion
TypeScript's type system is incredibly expressive. The more you lean into it, the more it rewards you with safer, self-documenting code.