TypeScript · Chapter 44 of 44

TypeScript Best Practices

Writing good TypeScript is about more than just adding type annotations everywhere — it's about using the type system to genuinely prevent bugs while keeping code readable and maintainable.

Following a few consistent habits, such as enabling strict mode, avoiding unnecessary `any`, and preferring precise types, will make your TypeScript projects much easier to work with as they grow.

Syntax
// Best practices, not new syntax

Key habits

Enable `strict` mode in tsconfig.json from the start of a project. Prefer `unknown` over `any` when a type is genuinely uncertain. Let TypeScript infer simple variable types instead of over-annotating.

Structuring types

Use interfaces or type aliases to name and reuse complex shapes instead of repeating them. Keep functions small with clear parameter and return types, especially in shared or public code.

Example 1 (typescript)
interface User {
  name: string;
  age: number;
}
function isAdult(user: User): boolean {
  return user.age >= 18;
}
console.log(isAdult({ name: "Zoe", age: 20 }));
Output
true

A named interface and a small function with clear types make this code easy to read and reuse.

Example 2 (typescript)
function parseInput(value: unknown): string {
  if (typeof value === "string") {
    return value.trim();
  }
  return String(value);
}
console.log(parseInput("  hi  "));
console.log(parseInput(42));
Output
hi
42

Using unknown instead of any forces a safe type check before the value is used.

Key points

  • Enable strict mode in every new TypeScript project.
  • Prefer unknown over any when a type is genuinely uncertain.
  • Let TypeScript infer obvious types instead of over-annotating everything.
  • Reuse interfaces and type aliases instead of repeating complex shapes.
💡 Note: The goal of TypeScript is to catch bugs early and document intent — good habits make both of those benefits stronger.

📝 Quick Quiz

1. What should you enable at the start of a new TypeScript project?

2. What is generally preferred over `any` for uncertain types?

3. Why reuse interfaces and type aliases?