TypeScript Tips for Cleaner, Safer Code

TypeScript helps you write fewer bugs and more reliable code. But it’s only as good as how you use it. Here are some practical tips.


1. Prefer unknown over any

function parseJson(str: string): unknown {
  return JSON.parse(str);
}

unknown forces you to check types before use, unlike any.


2. Use type aliases and interfaces wisely

  • Use type for unions and primitives.
  • Use interface for objects and contracts.

3. Leverage utility types

type UserPreview = Pick<User, "id" | "name">;

Built-in helpers like Pick, Partial, Omit save time and avoid duplication.


4. Avoid overcomplicating generics

Keep generics simple. Don’t make types harder than the code itself.


πŸš€ Key Takeaways

  • TypeScript is guardrails, not handcuffs.
  • Embrace strict mode.
  • Use types to document intent, not just silence the compiler.

Cleaner types = cleaner code.