Class vs Interface vs Type in TypeScript

TypeScript provides powerful tools to define the structure of your data and objects through classes, interfaces, and types. Understanding their differences is key to writing clean, scalable, and maintainable code.

🔹 Class

A class in TypeScript is a blueprint for creating objects with specific properties and methods. It supports object-oriented programming features like inheritance and encapsulation.

class Person {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

const p = new Person("Sharmin");
p.greet();

🔹 Interface

An interface defines the shape of an object. It’s purely for type-checking and doesn't compile into JavaScript. Interfaces can be extended and merged.

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "Sharmin",
  age: 22,
};

🔹 Type

A type alias can define not just object shapes, but also union types, tuples, primitives, and more. It is more flexible than interfaces.

type Product = {
  id: number;
  name: string;
};

type Status = "pending" | "shipped" | "delivered";

🔸 Key Differences

  • Class: Used to create actual objects and can have methods. Has a runtime presence.
  • Interface: Only for static type checking. Supports extension and declaration merging.
  • Type: More flexible. Can define unions, intersections, primitives, etc. Cannot be merged or extended like interfaces.

✅ Use interfaces for defining object shapes, types for flexibility, and classes for object-oriented logic with methods and inheritance.