TypeScript Tutorial · Classes and Enums · Lesson 14 of 25
TypeScript Classes
Typed fields, access modifiers, parameter properties, abstract classes and implements.
Typed classes
TypeScript adds types and access modifiers to JavaScript classes:
public(default),protected,private— checked at compile time.readonly— assignable only in the constructor.#private— JavaScript's runtime-private fields, also supported.
Parameter properties declare and assign a field straight from the constructor:
class Account {
private balance = 0;
constructor(public readonly owner: string, private readonly currency = "USD") {}
deposit(amount: number): this {
if (amount <= 0) throw new Error("Amount must be positive");
this.balance += amount;
return this;
}
get summary(): string {
return `${this.owner}: ${this.balance.toFixed(2)} ${this.currency}`;
}
}
const acct = new Account("Ada").deposit(50).deposit(25);
console.log(acct.summary);
// @ts-expect-error — Property 'balance' is private and only accessible within class 'Account'.
console.log(acct.balance); // still readable at runtime: use #balance for true privacy
Output
Ada: 75.00 USD 75
implements and abstract
implements checks that a class satisfies an interface; abstract classes can't be instantiated and may declare abstract methods:
interface Shape {
area(): number;
}
abstract class Base implements Shape {
abstract area(): number;
describe(): string {
return `${this.constructor.name} with area ${this.area().toFixed(2)}`;
}
}
class Circle extends Base {
constructor(private r: number) { super(); }
area() { return Math.PI * this.r ** 2; }
}
class Rect extends Base {
constructor(private w: number, private h: number) { super(); }
area() { return this.w * this.h; }
}
const shapes: Shape[] = [new Circle(1), new Rect(2, 3)];
for (const s of shapes) console.log((s as Base).describe());
Output
Circle with area 3.14 Rect with area 6.00
Test yourself
What does constructor(private name: string) do?
Only declares a parameterDeclares and assigns a private field named nameMakes the constructor privateNothing — it's invalid
Show answer
Answer: Declares and assigns a private field named name