10 TypeScript Tips for Writing Better Code
TypeScript has become the standard for modern web development. Here are 10 tips that will help you write better TypeScript code.
1. Use Strict Mode
Always enable strict mode in your tsconfig.json:
{
"compilerOptions": {
"strict": true
}
}2. Leverage Type Inference
Don't over-annotate. TypeScript can infer types:
// Unnecessary
const name: string = "John";// Better - TypeScript infers the type
const name = "John";
3. Use Union Types
Union types make your code more flexible:
type Status = "pending" | "approved" | "rejected";function updateStatus(status: Status) {
// TypeScript ensures only valid values are passed
}
4. Utilize Utility Types
TypeScript provides powerful utility types:
interface User {
id: number;
name: string;
email: string;
}// Make all properties optional
type PartialUser = Partial<User>;
// Make all properties required
type RequiredUser = Required<User>;
// Pick specific properties
type UserPreview = Pick<User, "id" | "name">;
5. Use const assertions
Const assertions create more specific types:
const config = {
endpoint: "/api",
timeout: 5000,
} as const;
// config.endpoint is now "/api" not string6. Generic Functions
Generics make your functions reusable:
function first<T>(arr: T[]): T | undefined {
return arr[0];
}const num = first([1, 2, 3]); // number
const str = first(["a", "b"]); // string
7. Type Guards
Type guards narrow types safely:
function isString(value: unknown): value is string {
return typeof value === "string";
}function process(value: unknown) {
if (isString(value)) {
console.log(value.toUpperCase()); // TypeScript knows it's a string
}
}
8. Use satisfies Operator
The satisfies operator validates types while preserving inference:
const palette = {
red: [255, 0, 0],
green: "#00ff00",
} satisfies Record<string, string | number[]>;9. Discriminated Unions
Create type-safe state machines:
type State =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: string }
| { status: "error"; error: Error };10. Template Literal Types
Create complex string types:
type EventName = on${Capitalize<string>};
// Matches "onClick", "onHover", etc.Conclusion
These TypeScript tips will help you write more robust and maintainable code. Remember, TypeScript is a tool to help you - use it wisely to catch bugs at compile time rather than runtime.
Happy coding!