Classes in TypeScript: A Comprehensive Guide
A class is a blueprint for creating objects. You define the shape once, then stamp out as many instances as you need.
23 Apr 2024

A class is a blueprint for creating objects. You define the shape once, then stamp out as many instances as you need.
TypeScript classes look like JavaScript classes, but with one critical addition: access modifiers and type annotations that catch mistakes before runtime.
class Person {
private name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
public sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
The private keyword means nothing outside this class can touch name or age directly. This is enforced at compile time only. At runtime, JavaScript has no concept of private (unless you use the # prefix).
Inheritance
Classes can extend other classes. The child gets everything the parent has, plus whatever you add.
class Employee extends Person {
private department: string;
constructor(name: string, age: number, department: string) {
super(name, age);
this.department = department;
}
public sayHello() {
super.sayHello();
console.log(`I work in the ${this.department} department.`);
}
}
The trade-off
Classes give you encapsulation, inheritance, and a familiar mental model if you come from Java or C#.
But TypeScript's type system is structural, not nominal. An object with the right shape satisfies an interface whether or not it was created by a class. In many codebases, plain objects and functions are simpler and more composable than class hierarchies.
I reach for classes when I need stateful objects with behavior. For data shapes and contracts, I use interfaces and types instead.