Lesson 40 of 50TypeScript
Classes in TypeScript
Add access modifiers, parameter properties, abstract classes, override, decorators and accessor to the JavaScript classes you know.
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:
| Modifier | Accessible from |
|---|---|
public (the default) | Anywhere |
protected | The class and its subclasses |
private | Only 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.
Press Run (⌘ Enter) to see what happens.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;
}
}class User {
constructor(
readonly id: number,
private email: string,
) {}
}readonly fields can be set in the declaration or the constructor, and never again. Like private, it is checked at compile time only.
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.
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'.An abstract class shares real code (describe) and demands the rest (area).
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.
Generic classes
Classes take type parameters like functions do. A typed cache is a common example:
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:
class Order {
constructor(private price: number) {}
total = this.price * 2;
// Error: Property 'price' is used before its initialization.
}class Order {
price;
constructor(price) {
this.price = price; // code TypeScript wrote for you
}
total = this.price * 2;
}
console.log(new Order(5).total); // NaNTwo 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.
In a subclass, nothing on this exists until super() returns. A base class skips this step.
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 = 12Legacy 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) | |
|---|---|---|
| Flag | none | experimentalDecorators: true |
| Signature | (value, context) | (target, key, descriptor) |
| Parameter decorators | No | Yes |
| Type metadata | No | With emitDecoratorMetadata |
| Used by | new code, Lit, MobX 6 | NestJS, 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); // 99accessor 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.
noImplicitOverride on, a base class method charge() is renamed to createCharge(). A subclass still has override charge(). What happens?erasableSyntaxOnly allow?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(" "));Match the feature to what it does.
A bank account class
Write a BankAccount class that protects its balance.
constructor(owner: string): use a parameter property soowneris a public,readonlyfield.- The balance (in cents) starts at
0and is stored in aprivatefield. get balance(): numberreturns it.deposit(cents: number): voidthrows anErrorunlesscentsis a positive integer.withdraw(cents: number): voidthrows 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"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 payloadImplement:
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.
- access modifier
public,protectedorprivateon 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.
noImplicitOverridemakes it required and checked. - decorator
- A function applied with
@namethat 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.