TypeScript Tips for Better Code
Practical TypeScript patterns and tips to write safer, more maintainable code.
TypeScriptJavaScriptBest Practices
TypeScript has transformed how we write JavaScript applications. Here are some practical tips I've learned along the way.
Use satisfies for Type Checking
The satisfies operator lets you validate that a value matches a type without widening it:
const config = {
apiUrl: "https://api.example.com",
timeout: 5000,
retries: 3,
} satisfies Record<string, string | number>;
Discriminated Unions
Use discriminated unions to model state machines:
type RequestState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; error: Error };
Template Literal Types
Create precise string types:
type EventName = `on${Capitalize<string>}`;
// Matches: "onClick", "onHover", "onSubmit", etc.
The infer Keyword
Extract types from other types:
type ReturnTypeOf<T> = T extends (...args: unknown[]) => infer R ? R : never;
These patterns will help you write more expressive and type-safe code. TypeScript's type system is incredibly powerful once you learn to leverage it effectively.