TypeScript Fundamentals

TypeScript adds static typing to JavaScript, making code more maintainable and catching errors early.

Type Definitions

// Basic types
type User = {
  id: number;
  name: string;
  email: string;
  active?: boolean;
};

// Union types
type Status = 'pending' | 'active' | 'inactive';

// Generic interfaces
interface Repository<T> {
  find(id: string): Promise<T>;
  save(item: T): Promise<T>;
}

Advanced Patterns

// Discriminated unions
type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'rectangle'; width: number; height: number };

function getArea(shape: Shape): number {
  switch (shape.kind) {
    case 'circle':
      return Math.PI * shape.radius ** 2;
    case 'rectangle':
      return shape.width * shape.height;
  }
}

Best Practices

  1. Use strict mode
{
  "compilerOptions": {
    "strict": true
  }
}
  1. Prefer interfaces for public APIs
  2. Use type inference when possible
  3. Leverage const assertions
  4. Implement proper error handling

Stay tuned for more TypeScript tips!