Advanced TypeScript Patterns
Here are some TypeScript patterns I’ve found particularly useful:
Type Predicates
Type predicates are functions that narrow down types:
function isError(value: unknown): value is Error {
return value instanceof Error;
}
Discriminated Unions
Perfect for handling different states:
type State =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; error: Error };