Skip to content

Lesson 40 of 50TypeScript

Classes in TypeScript

Add access modifiers, parameter properties, abstract classes, override, decorators and accessor to the JavaScript classes you know.

19 min read0/6 questions

You already know JavaScript classes: constructor, methods, extends, #private fields. TypeScript adds a layer on top that makes classes safer to share: who can touch which field, which methods a subclass must implement, and which contract a class promises to fulfil. You will meet these in NestJS services, Angular components, SDK clients, and any codebase with a domain model.

Typing fields and access modifiers

In TypeScript, every field a class uses must be declared with its type. Then each member can get an access modifier:

ModifierAccessible from
public (the default)Anywhere
protectedThe class and its subclasses
privateOnly inside the class itself
class Counter {
  public label: string;
  protected step = 1;
  private count = 0;
 
  constructor(label: string) {
    this.label = label;
  }
 
  increment(): number {
    this.count += this.step;
    return this.count;
  }
}
 
const c = new Counter("clicks");
c.increment();
c.count = 100;
// Error: Property 'count' is private and only accessible within class 'Counter'.

private vs JavaScript #private

TypeScript's private is a compile-time rule. It is erased like every other type annotation, so at runtime the field is an ordinary property anyone can read. JavaScript's #private fields are enforced by the engine itself.

TypeScript
class TsPrivate { private secret = "visible at runtime";} class JsPrivate { #secret = "truly hidden"; reveal() { return this.#secret; }} const a = new TsPrivate();const b = new JsPrivate(); console.log(Object.keys(a), JSON.stringify(a));console.log(Object.keys(b), JSON.stringify(b));console.log(b.reveal());
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Which statement is true?
Need a nudge? A hint rules out a wrong answer.

Parameter properties and readonly

Declaring a field, accepting it in the constructor and assigning it is so common that TypeScript has a shortcut. Put a modifier on a constructor parameter and it becomes a field automatically. This is a parameter property.

class User {
  readonly id: number;
  private email: string;
 
  constructor(id: number, email: string) {
    this.id = id;
    this.email = email;
  }
}

readonly fields can be set in the declaration or the constructor, and never again. Like private, it is checked at compile time only.

TypeScript
class Money { constructor( readonly amountCents: number, readonly currency: "USD" | "EUR", ) {} add(other: Money): Money { if (other.currency !== this.currency) throw new Error("Currency mismatch"); return new Money(this.amountCents + other.amountCents, this.currency); } toString(): string { return `${(this.amountCents / 100).toFixed(2)} ${this.currency}`; }} const total = new Money(1250, "USD").add(new Money(399, "USD"));console.log(total.toString());// total.amountCents = 0; // Error: Cannot assign to 'amountCents' because it is a read-only property.
Output
Press Run (⌘ Enter) to see what happens.

Money is a value object: immutable, so add returns a new instance instead of changing this one. Readonly fields make that intention enforceable.

Abstract classes

An abstract class is a base class you cannot instantiate directly. It can contain real, shared code, plus abstract methods: signatures with no body that every subclass must implement.

TypeScript
abstract class Shape { constructor(readonly name: string) {} abstract area(): number; describe(): string { return `${this.name} with area ${this.area().toFixed(1)}`; }} class Circle extends Shape { constructor(private radius: number) { super("circle"); } area(): number { return Math.PI * this.radius ** 2; }} class Square extends Shape { constructor(private side: number) { super("square"); } area(): number { return this.side ** 2; }} const shapes: Shape[] = [new Circle(1), new Square(3)];for (const s of shapes) console.log(s.describe());
Output
Press Run (⌘ Enter) to see what happens.
new Shape("blob");
// Error: Cannot create an instance of an abstract class.
 
class Triangle extends Shape {}
// Error: Non-abstract class 'Triangle' does not implement inherited abstract member 'area' from class 'Shape'.
Contracts and implementations
Shapeabstract: describe() shared, area() requiredCircleimplements area()Squareimplements area()Serializableinterface: toJSON()Moneyimplements Serializableroot

An abstract class shares real code (describe) and demands the rest (area).

1/3

Implementing interfaces

implements tells TypeScript to check that a class matches an interface. It adds nothing at runtime; it just makes the contract explicit and moves the error to the class definition.

interface Logger {
  log(message: string): void;
  error(message: string, cause?: unknown): void;
}
 
class ConsoleLogger implements Logger {
  log(message: string) { console.log(message); }
  error(message: string, cause?: unknown) { console.error(message, cause); }
}
 
class SilentLogger implements Logger {
  log() {}
  // Error: Class 'SilentLogger' incorrectly implements interface 'Logger'.
  //   Property 'error' is missing in type 'SilentLogger' but required in type 'Logger'.
}

Code that depends on Logger, not ConsoleLogger, can be handed any implementation: a test fake, a file logger, a cloud logger. That is dependency inversion, and interfaces are how TypeScript expresses it.

Abstract class or interface? Use an interface for a pure contract (most cases, and a class can implement many). Use an abstract class when subclasses should share code too, and accept that a class can only extend one.

Quick check
Which is true?
Need a nudge? A hint rules out a wrong answer.

Generic classes

Classes take type parameters like functions do. A typed cache is a common example:

TypeScript
class TtlCache<K, V> { private entries = new Map<K, { value: V; expires: number }>(); constructor(private ttlMs: number) {} set(key: K, value: V, now = Date.now()): void { this.entries.set(key, { value, expires: now + this.ttlMs }); } get(key: K, now = Date.now()): V | undefined { const entry = this.entries.get(key); if (!entry || entry.expires <= now) return undefined; return entry.value; }} const cache = new TtlCache<string, number>(1000);cache.set("views", 42, 0);console.log(cache.get("views", 500), cache.get("views", 1500));
Output
Press Run (⌘ Enter) to see what happens.

override and noImplicitOverride

Here is a bug that type checking used to miss. A base class has a hook that subclasses customise:

class PaymentProvider {
  charge(cents: number): string {
    return `default charge of ${cents}`;
  }
}
 
class StripeProvider extends PaymentProvider {
  charge(cents: number): string {
    return `stripe charge of ${cents}`;
  }
}

Months later someone renames the base method to createCharge and updates every caller. StripeProvider.charge still compiles, because a subclass is allowed to add new methods. It just no longer overrides anything. Every Stripe payment now runs the default code, and nothing turned red.

The override keyword says "this member must replace one from the base class". Turn on noImplicitOverride in tsconfig.json and the compiler insists on it, in both directions:

class StripeProvider extends PaymentProvider {
  override charge(cents: number): string { /* ... */ }
  // After the rename:
  // Error: This member cannot have an 'override' modifier because it is not declared in the base class 'PaymentProvider'.
}
 
class PaypalProvider extends PaymentProvider {
  createCharge(cents: number): string { /* ... */ }
  // Error: This member must have an 'override' modifier because it overrides a member in the base class 'PaymentProvider'.
}

The first error catches the rename. The second stops anyone from overriding by accident, which matters in big hierarchies where you do not know every method of the base class. Implementing an abstract member does not need override (there is nothing to replace), though writing it is allowed.

override is a pure annotation. It disappears at compile time, so unlike parameter properties it works with type stripping. If your codebase uses inheritance at all, noImplicitOverride is one of the cheapest strictness flags to adopt.

Parameter properties, field order and erasableSyntaxOnly

The note earlier said parameter properties are not erasable. Here is why, and the bug they hide. This is what tsc emits for a parameter property with a modern target:

order.ts
class Order {
  constructor(private price: number) {}
  total = this.price * 2;
  // Error: Property 'price' is used before its initialization.
}
order.js
class Order {
  price;
  constructor(price) {
    this.price = price; // code TypeScript wrote for you
  }
  total = this.price * 2;
}
console.log(new Order(5).total); // NaN

Two things stand out. First, the this.price = price line does not exist in your source. A type stripper, like the one built into Node, works by deleting type annotations and leaving everything else where it is. It cannot invent a statement. So erasableSyntaxOnly rejects parameter properties with "This syntax is not allowed when 'erasableSyntaxOnly' is enabled", along with enums and namespaces that contain code, for the same reason. You saw the flag in The TypeScript toolchain in 2026.

Second, the order. In modern JavaScript, class field initialisers run before the constructor body. Parameter property assignments are emitted inside the body, so total reads this.price while it is still undefined, and you get NaN. TypeScript reports the error above, but only if you are type checking. Older projects compiled with useDefineForClassFields: false (the default for older targets) moved initialisers into the constructor after the assignments, so the same code printed 10. Upgrading target is a classic way to discover this bug in an old codebase.

What runs when you call new Order(5)
  1. super(...)only in a subclass: the base class builds first
  2. field initialisers, top to bottomtotal = this.price * 2 runs here
  3. this.price = pricethe parameter property assignment
  4. the rest of the constructor bodyyour own statements

In a subclass, nothing on this exists until super() returns. A base class skips this step.

1/4

The long form from the start of this lesson avoids both problems. If you still want the brevity, compute derived values in the constructor body or as a getter (get total() { return this.price * 2; }), never in a field initialiser that reads a parameter property.

Decorators: the standard and the legacy version

A decorator is a function that wraps or annotates a class or member, written @name above it. TypeScript has two incompatible implementations, and which one you are using decides what code you can write.

Standard decorators follow the TC39 proposal and have worked in TypeScript since 5.0 with no flag. A method decorator receives the original method and a context object, and can return a replacement:

function logged<This, Args extends unknown[], Return>(
  method: (this: This, ...args: Args) => Return,
  context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
) {
  const name = String(context.name);
  return function (this: This, ...args: Args): Return {
    console.log(`-> ${name}(${args.join(", ")})`);
    const result = method.call(this, ...args);
    console.log(`<- ${name} = ${String(result)}`);
    return result;
  };
}
 
class PriceCalculator {
  @logged
  total(unitPrice: number, quantity: number): number {
    return unitPrice * quantity;
  }
}
 
new PriceCalculator().total(3, 4);
// -> total(3, 4)
// <- total = 12

Legacy decorators are switched on with "experimentalDecorators": true. They predate the standard, take different arguments (target, propertyKey, descriptor), and support two things the standard does not: parameter decorators and, with emitDecoratorMetadata, runtime type metadata. Dependency injection frameworks are built on exactly those. NestJS's @Injectable(), @Body() and @Inject() and TypeORM's @Column() rely on legacy decorators, and Angular has historically used them too. Check each framework's docs for the setting it currently expects.

Standard (TS 5.0+)Legacy (experimentalDecorators)
FlagnoneexperimentalDecorators: true
Signature(value, context)(target, key, descriptor)
Parameter decoratorsNoYes
Type metadataNoWith emitDecoratorMetadata
Used bynew code, Lit, MobX 6NestJS, TypeORM, older Angular

The practical rules: do not mix the two in one project, and do not copy a decorator from a blog post without checking which kind it is, because the signatures are not compatible. Decorators are runtime code, so they always need a compile step. Node's type stripping rejects them until JavaScript engines support the syntax natively.

Auto-accessors with accessor

The standard decorators came with a new class member keyword. accessor declares a field that is really a private storage slot plus a generated getter and setter:

class Cart {
  accessor quantity = 1;
}
// roughly the same as:
class CartLongForm {
  #quantity = 1;
  get quantity() { return this.#quantity; }
  set quantity(v: number) { this.#quantity = v; }
}

On its own that saves little. Its point is that a decorator on an accessor can intercept every read and write, which is how reactive libraries such as Lit implement @property() accessor name = "". A field decorator cannot do that, because a plain field is just a value on the instance. Here is a decorator that clamps every assignment:

function clamp(min: number, max: number) {
  return function <This>(
    target: ClassAccessorDecoratorTarget<This, number>,
    context: ClassAccessorDecoratorContext<This, number>,
  ): ClassAccessorDecoratorResult<This, number> {
    return {
      set(this: This, value: number) {
        target.set.call(this, Math.min(max, Math.max(min, value)));
      },
    };
  };
}
 
class Basket {
  @clamp(0, 99) accessor quantity = 1;
}
 
const basket = new Basket();
basket.quantity = 250;
console.log(basket.quantity); // 99

accessor needs a compile step today for the same reason decorators do. Reach for it when a library asks for it. In plain domain code, a normal getter and setter is clearer.

Quick check
With noImplicitOverride on, a base class method charge() is renamed to createCharge(). A subclass still has override charge(). What happens?
Need a nudge? A hint rules out a wrong answer.
Quick check
Which of these does erasableSyntaxOnly allow?
Need a nudge? A hint rules out a wrong answer.
Predict the outputTypeScript

What does this print?

class Animal {
protected sound = "...";
speak() { return this.sound; }
}
class Dog extends Animal {
protected sound = "woof";
}
const pets: Animal[] = [new Animal(), new Dog()];
console.log(pets.map((p) => p.speak()).join(" "));
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match the feature to what it does.

Choose an item, then its match on the other side.
ChallengeEasy

A bank account class

Write a BankAccount class that protects its balance.

  • constructor(owner: string): use a parameter property so owner is a public, readonly field.
  • The balance (in cents) starts at 0 and is stored in a private field.
  • get balance(): number returns it.
  • deposit(cents: number): void throws an Error unless cents is a positive integer.
  • withdraw(cents: number): void throws for the same bad input, and also throws (leaving the balance unchanged) if there is not enough money.
const acct = new BankAccount("Ada");
acct.deposit(500);
acct.withdraw(200);
acct.balance;       // 300
acct.withdraw(1000); // throws "Insufficient funds"
TypeScript
class BankAccount { constructor(public readonly owner: string) {} get balance(): number { return 0; } deposit(cents: number): void {} withdraw(cents: number): void {}}
ChallengeMedium

A typed event emitter

Write a generic TypedEmitter<Events> where Events maps each event name to its payload type:

type AppEvents = { login: { userId: number }; logout: undefined };
const bus = new TypedEmitter<AppEvents>();
bus.on("login", (p) => console.log(p.userId)); // p is { userId: number }
bus.emit("login", { userId: 7 });
bus.emit("login", { id: 7 }); // Error at compile time: wrong payload

Implement:

  • on(event, listener): registers a listener and returns an unsubscribe function.
  • emit(event, payload): calls every listener for that event, in the order they were added.

Emitting an event with no listeners does nothing.

TypeScript
class TypedEmitter<Events extends Record<string, unknown>> { // One optional array of listeners per event name (a mapped type, see the Advanced types lesson). private listeners: { [E in keyof Events]?: Array<(payload: Events[E]) => void>; } = {}; on<E extends keyof Events>( event: E, listener: (payload: Events[E]) => void, ): () => void { return () => {}; } emit<E extends keyof Events>(event: E, payload: Events[E]): void {}}
Key terms
access modifier
public, protected or private on a class member, controlling where it can be used. Checked at compile time.
#private field
A JavaScript private field enforced at runtime by the engine, invisible outside the class.
parameter property
A constructor parameter with a modifier (like readonly id: number) that declares and assigns a field in one go.
abstract class
A base class that cannot be instantiated. It can share code and declare abstract methods subclasses must implement.
implements
Checks that a class satisfies an interface. Adds nothing at runtime.
override
A modifier saying a member replaces one in the base class. noImplicitOverride makes it required and checked.
decorator
A function applied with @name that wraps or annotates a class or member. Standard (TS 5.0+) and legacy (experimentalDecorators) versions are incompatible.
auto-accessor
A field declared with accessor: private storage plus a generated getter and setter that decorators can intercept.