Classes and Objects
A class bundles data (properties) with the functions that operate on it (methods) — the same idea as in JavaScript, but TypeScript adds access modifiers that control where a property or method can be used from.
main.ts
Try it yourself →class Dog {
name: string;
private age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
bark(): string {
return `${this.name} says Woof! (age ${this.age})`;
}
}
const rex = new Dog("Rex", 3);
console.log(rex.name);
console.log(rex.bark());Output
Rex Rex says Woof! (age 3)
public, private, protected, and readonly
- public is the default — accessible from anywhere, including outside the class
- private is only accessible from inside the class itself — rex.age would be a compile error outside Dog
- protected is like private, but also accessible from subclasses
- readonly can be combined with any of the above, and can only be set once, usually in the constructor
Constructor shorthand
Writing this.name = name for every property gets repetitive — TypeScript lets you declare and assign a property directly in the constructor's parameter list instead.
main.ts
Try it yourself →class Point {
constructor(public x: number, public y: number) {}
toString(): string {
return `(${this.x}, ${this.y})`;
}
}
const p = new Point(3, 4);
console.log(p.toString());Output
(3, 4)
Next: generics — writing a function or type that works across many types, without giving up type safety.
Practice exercise
Write a class Account with a constructor that takes public balance: number, and a method deposit(amount: number): void that adds amount to balance. Create an Account with balance 100, deposit 50, then print account.balance.