Skip to content

TypeScript

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 · 2 min read

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.

TypeScript classes look like JavaScript classes, but with one critical addition: access modifiers and type annotations that catch mistakes before runtime.

Typescript
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.

Typescript
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.

Ehsan Gazar helps software engineers take LLM and agent systems from demo to production. He writes about building LLM systems that hold up in production: evals, tracing, RAG, agent architecture and cost control. He teaches the Senior to Staff AI Engineer cohort on Maven, where engineers learn to design and defend these systems.

Go further
Live cohort on Maven

Forward Deployed AI Engineering: From Customer Problem to Production Value

A live Maven cohort for engineers: 10 live 90-minute sessions taking one AI engagement from customer problem to production, ending with eight artefacts and a working slice in your own repo.

January cohort starts Tue 12 Jan 2027, Tue & Thu 6:30pm London. Enrolling now, 20 seats, $1,800.

View the live cohort

Keep reading