← Back to all tutorials

Classes

Object-oriented programming with TypeScript classes — constructors, methods, and properties.

Classes

TypeScript enhances JavaScript classes with typed properties and access modifiers.

Defining a Class

class Invoice {
    client: string;
    details: string;
    amount: number;

    constructor(c: string, d: string, a: number) {
        this.client = c;
        this.details = d;
        this.amount = a;
    }

    format(): string {
        return `${this.client} owes $${this.amount} for ${this.details}`;
    }
}

const invOne = new Invoice("Mario", "website work", 250);
console.log(invOne.format());
// "Mario owes $250 for website work"

Arrays of Class Instances

let invoices: Invoice[] = [];
invoices.push(new Invoice("Mario", "website", 250));
invoices.push(new Invoice("Luigi", "design", 300));

invoices.forEach(inv => console.log(inv.format()));

Property Access

By default, all class properties are public — they can be accessed and changed from outside:

const inv = new Invoice("Mario", "website", 250);
inv.client = "Luigi";   // ✅ Can modify
inv.amount = 500;       // ✅ Can modify
console.log(inv.client); // ✅ Can read

Key Takeaways

  • Classes define blueprints for objects with typed properties
  • Use constructors to initialize properties
  • Methods can have typed parameters and return types
  • Properties are public by default