🏗️ Classes TypeScript

class BankAccount {
  // Modificateurs d'accès
  private balance:   number;
  protected owner:  string;
  public id:         string;
  readonly createdAt: Date;

  constructor(owner: string, initialBalance: number = 0) {
    this.owner     = owner;
    this.balance   = initialBalance;
    this.id        = crypto.randomUUID();
    this.createdAt = new Date();
  }

  deposit(amount: number): void {
    if (amount <= 0) throw new Error("Amount must be positive");
    this.balance += amount;
  }

  getBalance(): number { return this.balance; }
}

const account = new BankAccount("Alice", 1000);
account.deposit(500);
console.log(account.getBalance()); // 1500
account.balance; // ❌ private — inaccessible

⚡ Parameter Properties (raccourci)

// Version longue
class Point {
  public x: number;
  public y: number;
  constructor(x: number, y: number) { this.x = x; this.y = y; }
}

// Version courte — parameter properties
class Point {
  constructor(public x: number, public y: number) {}
}

// Avec readonly et private
class User {
  constructor(
    public readonly id: number,
    public name: string,
    private password: string
  ) {}
}

🔗 Héritage & super

class Animal {
  constructor(public name: string) {}
  speak(): string { return `${this.name} fait un son`; }
}

class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name); // appel du constructeur parent obligatoire
  }
  speak(): string { return `${this.name} aboie`; }
  parentSpeak(): string { return super.speak(); }
}

const dog = new Dog("Rex", "Labrador");
dog.speak(); // "Rex aboie"

🎨 Classes abstraites & Interfaces

// Classe abstraite — ne peut pas être instanciée directement
abstract class Shape {
  abstract area(): number;         // méthode à implémenter
  abstract perimeter(): number;

  describe(): string {             // méthode concrète partagée
    return `Aire : ${this.area().toFixed(2)}`;
  }
}

class Circle extends Shape {
  constructor(private radius: number) { super(); }
  area()      { return Math.PI * this.radius ** 2; }
  perimeter() { return 2 * Math.PI * this.radius; }
}

// Interface d'implémentation
interface Serializable {
  serialize(): string;
  deserialize(data: string): void;
}

class Config implements Serializable {
  serialize()              { return JSON.stringify(this); }
  deserialize(data: string) { Object.assign(this, JSON.parse(data)); }
}

🔧 Getters & Setters

class Temperature {
  private _celsius: number = 0;

  get celsius(): number { return this._celsius; }

  set celsius(val: number) {
    if (val < -273.15) throw new Error("Below absolute zero");
    this._celsius = val;
  }

  get fahrenheit(): number { return this._celsius * 9/5 + 32; }
}

const t = new Temperature();
t.celsius = 100;
console.log(t.fahrenheit); // 212

📌 Static & Singleton

class MathUtils {
  static PI = 3.14159;
  static clamp(val: number, min: number, max: number): number {
    return Math.min(Math.max(val, min), max);
  }
}
MathUtils.clamp(150, 0, 100); // 100

// Pattern Singleton
class AppConfig {
  private static instance: AppConfig;
  private constructor() {}
  static getInstance(): AppConfig {
    if (!AppConfig.instance) AppConfig.instance = new AppConfig();
    return AppConfig.instance;
  }
}
📝 Exercices T04 🎯 QCM T04 ▶ Mini-projet T05 — Types avancés →