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.
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();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,
};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";✅ Use interfaces for defining object shapes, types for flexibility, and classes for object-oriented logic with methods and inheritance.