Explain it simply
Classes, in plain language
A class is a blueprint for objects that share the same data layout and the same behaviour. The blueprint says every Dog has a name and can bark(); new Dog("Buddy") builds one actual dog from it. Every object built from the class gets its own data but shares the methods.
TypeScript keeps JavaScript's class syntax and adds types: every field has a declared type, constructor parameters are typed, and access modifiers such as private tell the compiler which parts outside code may touch.
Problem → Why → Solution
The problem: data and rules living apart
Without classes you might build objects with a factory function and plain object literals. But if a bank account object exposes balance as an ordinary property, any code can write account.balance = 1000000, and if one of the three places that withdraw money forgets to check the balance, nobody notices. Nothing ties the data to the rules that are supposed to protect it.
function createAccount(owner: string) {
return { owner, balance: 0 };
}
const account = createAccount("Mya");
account.balance += 50; // deposit logic copied into every caller
account.balance = 1_000_000; // nothing stops this
account.balance -= 2_000_000; // overdraft: no rule is checkedWhat is missing
The data and the rules that guard it live apart. A class puts both in one place: fields hold the state, methods are the intended way to change it, and access modifiers let the compiler (or, with #private, the runtime) block direct writes from outside.
Core concept: blueprint, access and inheritance
A class declaration creates two things, just like an enum: a runtime value (the constructor function you call with new) and a type that describes its instances. In TypeScript every field is declared with a type at the top of the class. In strict mode the compiler checks that each field is initialised in its declaration or in the constructor, so you cannot accidentally create an object without a name.
Access modifiers control who may use a member. public, the default, means anyone; protected means the class and its subclasses; private means only the class itself. These three are TypeScript checks only. They are erased from the output, so plain JavaScript, JSON.stringify or a cast can still reach the value. JavaScript's own #private fields, written like #balance, are enforced by the runtime and are invisible outside the class body.
| Modifier | Who may access | Enforced by |
|---|---|---|
| public (default) | everyone | — |
| protected | the class and its subclasses | the compiler only |
| private | the class itself | the compiler only |
| #name | the class itself | the JavaScript runtime |
Inheritance lets one class build on another: class Dog extends Animal gets all of Animal's members and adds its own. A subclass constructor must call super(...) before it touches this, because the base class sets the object up first. When a subclass replaces a base method, mark it with override; with the noImplicitOverride option, forgetting the keyword is an error, which catches methods that silently stop overriding after a rename.
Finally, implements Interface asks the compiler to check that the class has every member the interface requires. It adds no code; it simply reports a mismatch at the class declaration instead of at some distant call site.
One base class, one subclass, one instance
------------------------------------------
class Animal base class
- private name: string
+ move(distance): void
^
| extends (inherits move, adds bark)
|
class Dog subclass
+ bark(): void
|
| new Dog("Buddy")
v
dog { name: "Buddy" } own data on the instance;
bark and move found on the prototypes- Class = constructor value + instance type
- Fields are typed, set in the constructor
- Modifiers decide who may touch them
- extends + super() build on a base
private is a promise kept by the compiler; #private is a lock kept by the runtime.
General pattern
class Name extends Base implements Contract {
#secret: Type; // runtime-private field
protected shared: Type; // the class and its subclasses
constructor(public readonly id: IdType, value: Type) {
super(/* base constructor arguments */);
this.#secret = value;
this.shared = value;
}
override method(param: Type): Result { /* ... */ }
}Declare typed fields, and in the constructor call super() before using this. A parameter property such as public readonly id declares and assigns a field in one step.
Animal and Dog
The example has a base class with a private field and a public method, and a subclass that adds one new method. Notice that Dog declares neither a constructor nor a name field of its own; everything it needs in order to move comes from Animal. Each console.log call prints its own line, so the output has two lines.
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public move(distance: number): void {
console.log(`${this.name} moved ${distance}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
const dog = new Dog("Buddy");
dog.bark();
dog.move(10);Code breakdown
- Line 2
private name: string;A typed field declaration. It is private, so only Animal's own code can read it; this.name inside Dog and dog.name outside are compile errors.
- Lines 4-6
constructor(name: string) {Runs on new and assigns the field. Remove that assignment and strict mode reports that name is never initialised.
- Line 8
public move(distance: number): void {A public method (public is the default, so writing it is optional). The parameter is typed and void says it returns nothing.
- Line 13
class Dog extends Animal {Dog inherits Animal's constructor and move, and adds bark. Dog has no constructor of its own, so new Dog("Buddy") uses Animal's.
- Line 21
dog.move(10);Calls the inherited method on a Dog. Animal's constructor already set name, so it prints Buddy moved 10m.
Woof! Woof!
Buddy moved 10m.Abstract classes, parameter properties, override and implements
The example below combines every part of this lesson. An abstract class cannot be created with new directly; its subclasses must fill in the abstract methods. Parameter properties such as constructor(private radius: number) are a shorthand for a field declaration plus assignment, but, like enums, they generate code, so type-stripping tools and the erasableSyntaxOnly option reject them.
interface Shape {
area(): number;
describe(): string;
}
abstract class BaseShape implements Shape {
constructor(public readonly label: string) {}
abstract area(): number;
describe(): string {
return `${this.label}: ${this.area().toFixed(2)}`;
}
}
class Circle extends BaseShape {
constructor(private radius: number) {
super("circle");
}
area(): number {
return Math.PI * this.radius ** 2;
}
}
class Square extends BaseShape {
constructor(private side: number) {
super("square");
}
area(): number {
return this.side ** 2;
}
override describe(): string {
return `${super.describe()} (side ${this.side})`;
}
}
const shapes: Shape[] = [new Circle(1), new Square(3)];
shapes.forEach((s) => console.log(s.describe()));
// circle: 3.14
// square: 9.00 (side 3)In real projects
Real project: custom error classes
Backend code uses classes for service objects (UserService, OrderRepository) and for the controllers some frameworks expect. The place beginners benefit from fastest, though, is custom errors. Unlike interfaces, classes exist at runtime, so you can test for them with instanceof, which lets one error handler choose the HTTP status from the type of the error:
class HttpError extends Error {
constructor(
public readonly status: number,
message: string,
) {
super(message);
this.name = "HttpError";
}
}
class NotFoundError extends HttpError {
constructor(resource: string) {
super(404, `${resource} not found`);
this.name = "NotFoundError";
}
}
function toResponse(err: unknown): string {
if (err instanceof HttpError) return `${err.status} ${err.message}`;
return "500 Internal Server Error";
}
console.log(toResponse(new NotFoundError("Order 42"))); // 404 Order 42 not found
console.log(toResponse(new Error("boom"))); // 500 Internal Server ErrorRoute handlers simply throw new NotFoundError("Order 42"), and the status code is decided in one place. A new kind of error is just one more subclass, and because instanceof HttpError also matches NotFoundError, the handler needs no change. Setting this.name means logs show "NotFoundError" instead of a plain "Error", which makes production problems faster to track down.
Common mistakes
Common mistakes
1. Believing private hides data at runtime
JSON.stringify on an object with private secret = 1 prints {"secret":1}, console.log shows it too, and (obj as any).secret = 5 works. For data that must really stay hidden, such as tokens or passwords, use #secret, which the runtime enforces.
2. Losing this when passing a method as a callback
Writing ["pen"].forEach(cart.add) leaves this undefined inside add, and it crashes with TypeError: Cannot read properties of undefined, while the compiler says nothing. Wrap it in an arrow function, (item) => cart.add(item), or write the method as an arrow-function property, add = (item: string) => { ... }.
3. Using this before super(), or hiding fields with !
Writing this.x = 1 before super() in a subclass constructor gives error TS17009; call super() first. Silencing "has no initializer" with a definite-assignment ! (name!: string) only hides a field that may be undefined; assign it in the constructor instead.
Best practices
Best practices
- Use a class when state and rules really belong together; for plain data an interface and an object literal are enough.
- Use #private for data that must truly stay hidden, and private for everything else.
- Turn on noImplicitOverride in tsconfig and mark every replaced method with override.
- Keep inheritance one or two levels deep; when it grows tangled, consider composition instead.
Mini challenge
A bank account and a savings account
Write an account class that protects its balance in a runtime-private field and keeps the rules inside its methods, then extend it with a subclass that adds interest.
- BankAccount has a readonly owner and a #balance that starts at 0.
- deposit throws an Error for amounts of 0 or less; withdraw throws "Insufficient funds" when the amount exceeds the balance.
- Add getBalance() and describe() (formatted like "Mya: 408").
- SavingsAccount extends BankAccount with a rate, an addInterest() method and an override of describe().
class BankAccount {
// TODO: a runtime-private #balance field starting at 0
constructor(readonly owner: string) {}
deposit(amount: number): void {
// TODO: throw for amount <= 0, otherwise add to the balance
}
withdraw(amount: number): void {
// TODO: throw "Insufficient funds" when amount > balance
}
// TODO: getBalance(): number and describe(): string
}
// TODO: class SavingsAccount extends BankAccount
// - constructor(owner, rate) calls super(owner)
// - addInterest() deposits Math.round(balance * rate)
// - override describe() appends " (savings, 2%)"
// TODO: deposit 500, withdraw 100, add interest, print describe(),
// then try to withdraw 10000 and print the error messageExpected: Two lines: "Mya: 408 (savings, 2%)" and "Insufficient funds".
Show hint
The subclass cannot see #balance directly; use getBalance() and deposit(). When overriding describe(), reuse the base version with super.describe().
Show solution
class BankAccount {
#balance = 0;
constructor(readonly owner: string) {}
deposit(amount: number): void {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#balance += amount;
}
withdraw(amount: number): void {
if (amount > this.#balance) throw new Error("Insufficient funds");
this.#balance -= amount;
}
getBalance(): number {
return this.#balance;
}
describe(): string {
return `${this.owner}: ${this.#balance}`;
}
}
class SavingsAccount extends BankAccount {
constructor(owner: string, private rate: number) {
super(owner);
}
addInterest(): void {
this.deposit(Math.round(this.getBalance() * this.rate));
}
override describe(): string {
return `${super.describe()} (savings, ${this.rate * 100}%)`;
}
}
const savings = new SavingsAccount("Mya", 0.02);
savings.deposit(500);
savings.withdraw(100);
savings.addInterest();
console.log(savings.describe());
try {
savings.withdraw(10_000);
} catch (err) {
console.log(err instanceof Error ? err.message : err);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A class creates a constructor value and an instance type; strict mode checks every field is initialised.
- public, protected and private are compile-time checks; #private is enforced by the runtime.
- extends reuses a base class: call super() before this, and mark replaced methods with override.
- implements checks a class against an interface, and because classes exist at runtime, instanceof works on them.
TypeScript Handbook — TypeScript