DEV Community

Cover image for Types vs Interfaces in TypeScript: Which Should You Choose?
Lingaraj H U
Lingaraj H U

Posted on

Types vs Interfaces in TypeScript: Which Should You Choose?

Are you new to TypeScript and wondering about the difference between types and interfaces? Let's break it down with some cool examples!

🔹 Types: The Swiss Army Knife.

Types in TypeScript are super flexible. They're like the Swiss Army knife of type definitions.

// Define an object type for a superhero
type Superhero = {
  name: string;
  power: string;
  flyable?: boolean;  // Optional property
};

// Create a union type for a limited set of color options
type Color = "red" | "blue" | "green";

// Define a function type for mathematical operations
type MathFunction = (x: number, y: number) => number;

Enter fullscreen mode Exit fullscreen mode

🔹 Interfaces: The Blueprint

Interfaces are like blueprints for objects. They're great for defining the structure of classes.

// Define an interface for a vehicle
interface Vehicle {
  brand: string;
  speed: number;
  accelerate(): void;  // Method signature
}

// Implement the Vehicle interface in a Car class
class Car implements Vehicle {
  brand: string;
  speed: number;

  constructor(brand: string) {
    this.brand = brand;
    this.speed = 0;
  }

  // Implement the accelerate method
  accelerate() {
    this.speed += 10;
  }
}

Enter fullscreen mode Exit fullscreen mode

🔥 Key Differences:

  1. Union Types: Only possible with 'type'
// Union type (only possible with 'type')
type Status = "pending" | "approved" | "rejected";

Enter fullscreen mode Exit fullscreen mode
  1. Extending: Both can extend, but interfaces are more natural for OOP
// Extending an interface
interface Animal {
  name: string;
}
interface Dog extends Animal {
  bark(): void;
}

// Extending a type
type Shape = {
  color: string;
}
type Circle = Shape & {
  radius: number;
}
Enter fullscreen mode Exit fullscreen mode
  1. Declaration Merging: Only interfaces can be reopened to add new properties.
// Declaration merging (only possible with interfaces)
interface Book {
  title: string;
}
interface Book {
  author: string;
}
// Now Book has both title and author properties
Enter fullscreen mode Exit fullscreen mode

💡 Dev Tip: Use interfaces for objects and classes, and types for functions, unions, and complex types.

Remember, whether you use types or interfaces, TypeScript has got your back in catching errors before runtime!

Top comments (0)