Type Annotations Best Practices in TypeScript 🏷️TS

Type Annotations Best Practices in TypeScript 🏷️TS

Essential guidance on where and when to use type annotations for maximum clarity and type safety.

Core Principles

// ✅ Good: Explicit function signatures
function calculateTotal(items: CartItem[]): number {
  let sum = 0;  // Type inference OK for locals
  for (const item of items) {
    sum += item.price;
  }
  return sum;
}

// ✅ Good: Explicit object literals
const config: ServerConfig = {
  port: 8080,
  host: 'localhost'
};

// ❌ Avoid: Unnecessary local variable annotations
let count: number = 0;  // Type inference is sufficient

When to Use Type Annotations

  1. Function/Method Signatures

    • Parameters
    • Return types
    • Class methods
  2. Object Literals

    • Configuration objects
    • API responses
    • Complex data structures
  3. Exported Interfaces/Types

    • Public API definitions
    • Shared type definitions

When to Skip Annotations

Key Insight

Variables may change values during execution, but their types typically remain constant - leverage TypeScript's type inference for these cases.

References

Notes

🔍 #typescript #type-annotations #best-practices #type-inference


From: Vanderkam-Effective TypeScript