Cours JavaScript et TypeScript · Module 7: TypeScript avancé

Implémenter des interfaces

25 min de lecture ·
Dans cette leçon10

« À Jurassic Park, tout doit fonctionner selon des protocoles stricts », explique Claire Dearing, la directrice des opérations. « Chaque employé a un périmètre de responsabilités clairement défini, et chaque système doit répondre à des exigences précises. Peu nous importe comment exactement un garde surveille l'enclos des raptors - ce qui compte, c'est qu'il fasse son travail conformément aux procédures de sécurité. »

Dans le monde de TypeScript, les interfaces jouent un rôle similaire - elles définissent un « contrat » que les classes doivent respecter, sans préciser comment exactement elles doivent le faire. Dans cet exercice, tu apprendras à concevoir et à implémenter des interfaces en créant un système avancé de gestion pour Jurassic Park.

Les bases des interfaces

Une interface en TypeScript est une structure qui définit la forme d'un objet - quelles propriétés et méthodes il doit avoir, sans préciser leur implémentation. Tu peux voir une interface comme un contrat ou un protocole qu'une classe doit respecter.

Regardons la syntaxe de base d'une interface :

// Interface definition
interface ParkEmployee {
  // Properties
  id: string;
  firstName: string;
  lastName: string;
  accessLevel: number;

  // Methods
  login(): void;
  logout(): void;
  checkPermissions(requiredLevel: number): boolean;
}

// Class implementing the interface
class ParkGuard implements ParkEmployee {
  // Implementation of all required properties
  id: string;
  firstName: string;
  lastName: string;
  accessLevel: number;
  private activeStatus: boolean = false;

  constructor(id: string, firstName: string, lastName: string) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.accessLevel = 2; // Niveau standard pour le guard
  }

  // Implementation of all required methods
  login(): void {
    console.log(`Guard ${this.firstName} ${this.lastName} logged into the system.`);
    this.activeStatus = true;
  }

  logout(): void {
    console.log(`Guard ${this.firstName} ${this.lastName} logged out of the system.`);
    this.activeStatus = false;
  }

  checkPermissions(requiredLevel: number): boolean {
    return this.accessLevel >= requiredLevel;
  }

  // Additional methods specific to the guard
  patrolSector(sectorId: string): void {
    if (!this.activeStatus) {
      console.log("Error: Guard must be logged in to patrol sector.");
      return;
    }

    console.log(`Guard ${this.firstName} ${this.lastName} is patrolling sector ${sectorId}.`);
  }
}

// Another class implementing the same interface
class ParkScientist implements ParkEmployee {
  id: string;
  firstName: string;
  lastName: string;
  accessLevel: number;
  private specialization: string;

  constructor(id: string, firstName: string, lastName: string, specialization: string) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.accessLevel = 4; // Higher access level for scientists
    this.specialization = specialization;
  }

  login(): void {
    console.log(`Dr ${this.firstName} ${this.lastName} logged into the laboratory system.`);
  }

  logout(): void {
    console.log(`Dr ${this.firstName} ${this.lastName} logged out of the laboratory system.`);
  }

  checkPermissions(requiredLevel: number): boolean {
    // Scientists have special permissions in laboratories
    if (requiredLevel === 3 && this.specialization === "genetics") {
      return true;
    }
    return this.accessLevel >= requiredLevel;
  }

  // Method specific to the scientist
  conductResearch(researchSubject: string): void {
    console.log(`Dr ${this.firstName} ${this.lastName} is conducting research on: ${researchSubject}.`);
  }
}

// Using classes implementing the interface
const guard = new ParkGuard("SEC-001", "John", "Smith");
const scientist = new ParkScientist("SCI-042", "Henry", "Wu", "genetics");

// Both classes implement the same interface, so we can use the same methods
guard.login();
scientist.login();

// Checking permissions
console.log(`Guard has access to zone 2: ${guard.checkPermissions(2)}`);
console.log(`Scientist has access to zone 3: ${scientist.checkPermissions(3)}`);

// Calling methods specific to particular classes
guard.patrolSector("B-5");
scientist.conductResearch("DNA Velociraptor");

Dans l'exemple ci-dessus :

  1. Nous avons défini l'interface ParkEmployee précisant quelles propriétés et méthodes chaque employé doit avoir
  2. Nous avons créé deux classes différentes implémentant cette interface - chacune à sa manière
  3. Les deux classes doivent fournir toutes les propriétés et méthodes requises, mais peuvent les implémenter différemment
  4. Les classes peuvent aussi ajouter leurs propres méthodes et propriétés supplémentaires

Propriétés optionnelles et en lecture seule

Les interfaces TypeScript permettent des définitions de propriétés plus avancées :

interface SecuritySystem {
  // Required property
  id: string;

  // Read-only property - cannot be modified after initialization
  readonly systemType: "monitoring" | "fence" | "motionSensor" | "alarm";

  // Optional property - may or may not exist
  advancedOptions?: Record<string, any>;

  // Methods
  activate(): void;
  deactivate(): void;
  checkStatus(): string;
}

class FenceSystem implements SecuritySystem {
  id: string;
  readonly systemType: "monitoring" | "fence" | "motionSensor" | "alarm" = "fence";
  advancedOptions?: Record<string, any>; // Optional property

  private voltage: number = 0;
  private active: boolean = false;

  constructor(id: string, advancedOptions?: Record<string, any>) {
    this.id = id;
    if (advancedOptions) {
      this.advancedOptions = advancedOptions;
    }
  }

  activate(): void {
    this.active = true;
    this.voltage = this.advancedOptions?.startingVoltage || 10000; // Using optional property
    console.log(`System fence ${this.id} activated. Voltage: ${this.voltage}V`);
  }

  deactivate(): void {
    this.active = false;
    this.voltage = 0;
    console.log(`Fence system ${this.id} deactivated.`);
  }

  checkStatus(): string {
    return `System fence ${this.id}: ${this.active ? "ACTIVE" : "INACTIVE"}, Voltage: ${this.voltage}V`;
  }

  // Custom method, not required by the interface
  increaseVoltage(increment: number): void {
    if (!this.active) {
      console.log("Cannot change voltage - system inactive.");
      return;
    }

    this.voltage += increment;
    console.log(`Increased voltage to ${this.voltage}V.`);
  }
}

// Usage with optional properties
const tRexFence = new FenceSystem("FNC-TR1", {
  startingVoltage: 20000,
  automaticRestarts: true
});

const standardFence = new FenceSystem("FNC-ST1");

tRexFence.activate();   // Uses custom starting voltage
standardFence.activate();  // Uses default starting voltage

// Error: Cannot assign to 'systemType' because it is a read-only property
// tRexFence.systemType = "alarm";

Dans cet exemple :

  1. Nous avons défini une propriété readonly qui ne peut pas être modifiée après l'initialisation
  2. Nous avons ajouté une propriété optionnelle advancedOptions (marquée d'un ?)
  3. L'implémentation vérifie si la propriété optionnelle existe avant de l'utiliser

Étendre des interfaces

Les interfaces, comme les classes, peuvent étendre d'autres interfaces, en héritant de leurs propriétés et méthodes :

// Basic interface for all animals
interface Animal {
  id: string;
  species: string;
  weight: number;
  feed(): void;
  monitor(): string;
}

// Extended interface specific to dinosaurs
interface Dinosaur extends Animal {
  dangerLevel: number;
  dinosaurEra: "trias" | "jura" | "cretaceous";
  getSpecialDiet(): string;
}

// Even more specialized interface
interface PredatoryDinosaur extends Dinosaur {
  biteForce: number;
  speed: number;
  hunt(): void;
}

// Implementation
class TyrannosaurusRex implements PredatoryDinosaur {
  // Properties from Animal interface
  id: string;
  species: string = "Tyrannosaurus Rex";
  weight: number;

  // Properties from Dinosaur interface
  dangerLevel: number = 10;
  dinosaurEra: "trias" | "jura" | "cretaceous" = "cretaceous";

  // Properties from PredatoryDinosaur interface
  biteForce: number;
  speed: number;

  // Custom properties
  private age: number;
  private lastFeeding: Date | null = null;

  constructor(id: string, weight: number, age: number, biteForce: number, speed: number) {
    this.id = id;
    this.weight = weight;
    this.age = age;
    this.biteForce = biteForce;
    this.speed = speed;
  }

  // Implementation of methods from Animal interface
  feed(): void {
    this.lastFeeding = new Date();
    console.log(`T-Rex ${this.id} was fed.`);
  }

  monitor(): string {
    const feedingStatus = this.lastFeeding
      ? `Last feeding: ${this.lastFeeding.toLocaleString()}`
      : "No feeding information";

    return `T-Rex ${this.id}: Weight: ${this.weight}kg, Age: ${this.age} years. ${feedingStatus}`;
  }

  // Implementation of method from Dinosaur interface
  getSpecialDiet(): string {
    return "Fresh mammal meat, preferably beef, 250kg daily.";
  }

  // Implementation of method from PredatoryDinosaur interface
  hunt(): void {
    console.log(`T-Rex ${this.id} hunts at speed ${this.speed} km/h and bite force ${this.biteForce} PSI!`);
  }
}

// Usage
const rex = new TyrannosaurusRex("TREX-01", 8000, 12, 12800, 30);
rex.feed();
console.log(rex.monitor());
console.log(`Special diet: ${rex.getSpecialDiet()}`);
rex.hunt();

Dans cet exemple, nous avons créé une hiérarchie d'interfaces :

  1. Animal - l'interface de base pour tous les animaux
  2. Dinosaur - étend Animal avec des propriétés propres aux dinosaures
  3. PredatoryDinosaur - étend Dinosaur avec des propriétés propres aux prédateurs

La classe TyrannosaurusRex implémente l'interface la plus spécialisée PredatoryDinosaur, ce qui signifie qu'elle doit fournir toutes les propriétés et méthodes des trois interfaces.

Interfaces vs types

TypeScript propose aussi les alias de type (type), qui ont des capacités similaires aux interfaces, mais il existe quelques différences entre eux :

// Interface
interface EnclosureMeasurement {
  width: number;
  length: number;
  calculateArea(): number;
}

// Type (Type alias)
type CageMeasurement = {
  width: number;
  height: number;
  depth: number;
  calculateVolume(): number;
};

// Extending an interface
interface EnclosureMeasurementWithFence extends EnclosureMeasurement {
  fenceHeight: number;
  fenceMaterial: string;
}

// "Extending" a type through intersection
type ReinforcedCageMeasurement = CageMeasurement & {
  reinforcementMaterial: string;
  maxLoad: number;
};

// Implementation of interface
class RaptorEnclosure implements EnclosureMeasurementWithFence {
  width: number;
  length: number;
  fenceHeight: number;
  fenceMaterial: string;

  constructor(width: number, length: number, fenceHeight: number) {
    this.width = width;
    this.length = length;
    this.fenceHeight = fenceHeight;
    this.fenceMaterial = "Reinforced steel";
  }

  calculateArea(): number {
    return this.width * this.length;
  }
}

// Implementation of type (works the same as interface)
class TransportCage implements ReinforcedCageMeasurement {
  width: number;
  height: number;
  depth: number;
  reinforcementMaterial: string;
  maxLoad: number;

  constructor(
    width: number,
    height: number,
    depth: number,
    maxLoad: number
  ) {
    this.width = width;
    this.height = height;
    this.depth = depth;
    this.reinforcementMaterial = "Carbon composite";
    this.maxLoad = maxLoad;
  }

  calculateVolume(): number {
    return this.width * this.height * this.depth;
  }
}

Principales différences entre interfaces et types :

  1. Extensibilité :

    • Les interfaces peuvent être étendues ultérieurement (fusion de déclarations)
    • Les types sont fermés après leur définition
    // Interface can be extended with additional declarations
    interface DinosaurDiagnosis {
      examinationResult: string;
    }
    
    // Adding new properties to an existing interface
    interface DinosaurDiagnosis {
      executionDate: Date;
    }
    
    // Now DinosaurDiagnosis has both properties!
    
    // For types this won't work:
    type EnclosureDescription = {
      id: string;
    };
    
    // Error: Duplicate identifier 'EnclosureDescription'
    // type EnclosureDescription = {
    //   name: string;
    // };
  2. Combinaison :

    • Les interfaces utilisent extends
    • Les types utilisent l'opérateur d'intersection &
  3. Constructions avancées :

    • Les types peuvent représenter des unions, des intersections et d'autres types complexes
    • Les interfaces se limitent à décrire la forme des objets
// Advanced types that cannot be expressed with interfaces
type DinosaurStatus = "healthy" | "sick" | "in_treatment" | "quarantined";

type DinosaurID = string | number;

type AnimalOrPlant = Animal | { genus: string, height: number };

// Mapped types
type Optional<T> = {
  [P in keyof T]?: T[P];
};

// Using a mapped type with an interface
type OptionalDinosaur = Optional<Dinosaur>;

Interfaces pour les fonctions et les méthodes

Les interfaces peuvent aussi définir la forme des fonctions et des constructeurs de classe :

// Interface for a function
interface PhotoProcessing {
  (path: string, options?: { resolution?: number, filter?: string }): Promise<string>;
}

// Implementation of a function conforming to the interface
const dinosaurPhotoProcessor: PhotoProcessing = async (path, options) => {
  console.log(`Processing photo: ${path}`);
  console.log(`Options: ${JSON.stringify(options || {})}`);

  // Simulation of processing
  await new Promise(resolve => setTimeout(resolve, 1000));

  return `optimized_${path}`;
};

// Calling the function
dinosaurPhotoProcessor("trex.jpg", { resolution: 1200 })
  .then(result => console.log(`Processed: ${result}`));

// Interface for a class constructor
interface DinosaurConstructor {
  new (id: string, species: string, age: number): Animal;
}

// Function using a constructor
function createDinosaur(Constructor: DinosaurConstructor, id: string, species: string, age: number): Animal {
  return new Constructor(id, species, age);
}

// Class conforming to the constructor interface
class DinosaurPrototype implements Animal {
  id: string;
  species: string;
  weight: number = 0;
  private _age: number;

  constructor(id: string, species: string, age: number) {
    this.id = id;
    this.species = species;
    this._age = age;

    // Weight calculation based on age
    this.weight = age * 100; // Simplified calculation
  }

  feed(): void {
    console.log(`Feeding prototype ${this.species}.`);
  }

  monitor(): string {
    return `Monitoring prototype ${this.species} (ID: ${this.id}).`;
  }
}

// Using the factory function
const newDinosaur = createDinosaur(DinosaurPrototype, "PROTO-1", "Testosaurus", 5);
console.log(newDinosaur.monitor());

Signatures d'index dans les interfaces

Les interfaces peuvent aussi définir des types indexés qui permettent un accès dynamique aux propriétés :

// Interface with index signatures
interface AnimalDatabase {
  // String index, values of type Animal
  [id: string]: Animal;

  // We can also add specific properties
  animalCount: number;
  lastUpdate: Date;
}

// Implementation
class AnimalRepository implements AnimalDatabase {
  // Implementation of index
  [id: string]: Animal | number | Date | Function;

  animalCount: number = 0;
  lastUpdate: Date = new Date();

  // We need to handle methods, because they are also properties
  addAnimal(animal: Animal): void {
    this[animal.id] = animal;
    this.animalCount++;
    this.lastUpdate = new Date();
  }

  getAnimal(id: string): Animal | undefined {
    const animal = this[id];
    if (animal && typeof animal !== 'number' && !(animal instanceof Date) && typeof animal !== 'function') {
      return animal;
    }
    return undefined;
  }
}

// Usage
const animalRepo = new AnimalRepository();

// Adding some animals
const triceratops = {
  id: "TRIC-01",
  species: "Triceratops",
  weight: 6000,
  feed(): void { console.log("Feeding Triceratops"); },
  monitor(): string { return "Monitoring Triceratops"; }
};

const stegosaurus = {
  id: "STEG-01",
  species: "Stegosaurus",
  weight: 5000,
  feed(): void { console.log("Feeding Stegosaurus"); },
  monitor(): string { return "Monitoring Stegosaurus"; }
};

animalRepo.addAnimal(triceratops);
animalRepo.addAnimal(stegosaurus);

// Access through indexes
const animal = animalRepo.getAnimal("TRIC-01");
if (animal) {
  console.log(`Found: ${animal.species}`);
  animal.feed();
}

console.log(`Number of animals in repository: ${animalRepo.animalCount}`);
console.log(`Last update: ${animalRepo.lastUpdate.toLocaleString()}`);

Implémenter plusieurs interfaces

Une classe peut implémenter plusieurs interfaces en même temps :

// Interface for monitoring capability
interface Monitorable {
  startMonitoring(): void;
  stopMonitoring(): void;
  getMonitoringStatus(): string;
}

// Interface for alarm systems
interface AlarmSystem {
  startAlarm(): void;
  disableAlarm(): void;
  isAlarmActive: boolean;
}

// Interface for access control systems
interface AccessControl {
  checkAccess(permissionLevel: number): boolean;
  blockAccess(): void;
  unblockAccess(): void;
}

// Class implementing all three interfaces
class AdvancedSecuritySystem implements Monitorable, AlarmSystem, AccessControl {
  private id: string;
  private activeMonitoring: boolean = false;
  isAlarmActive: boolean = false;
  private accessBlocked: boolean = false;
  private minimumPermissionLevel: number;

  constructor(id: string, minimumPermissionLevel: number = 3) {
    this.id = id;
    this.minimumPermissionLevel = minimumPermissionLevel;
  }

  // Implementation of Monitorable
  startMonitoring(): void {
    this.activeMonitoring = true;
    console.log(`System ${this.id}: Monitoring started.`);
  }

  stopMonitoring(): void {
    this.activeMonitoring = false;
    console.log(`System ${this.id}: Monitoring stopped.`);
  }

  getMonitoringStatus(): string {
    return `System ${this.id}: Monitoring ${this.activeMonitoring ? "active" : "inactive"}`;
  }

  // Implementation of AlarmSystem
  startAlarm(): void {
    this.isAlarmActive = true;
    this.blockAccess(); // Automatic access block
    console.log(`System ${this.id}: !!! ALARM STARTED !!!`);
  }

  disableAlarm(): void {
    this.isAlarmActive = false;
    console.log(`System ${this.id}: Alarm disabled.`);
  }

  // Implementation of AccessControl
  checkAccess(permissionLevel: number): boolean {
    if (this.accessBlocked) {
      console.log(`System ${this.id}: Access blocked for all permission levels.`);
      return false;
    }

    const accessGranted = permissionLevel >= this.minimumPermissionLevel;
    console.log(`System ${this.id}: Checking access for level ${permissionLevel}: ${accessGranted ? "GRANTED" : "DENIED"}`);
    return accessGranted;
  }

  blockAccess(): void {
    this.accessBlocked = true;
    console.log(`System ${this.id}: Access blocked.`);
  }

  unblockAccess(): void {
    if (this.isAlarmActive) {
      console.log(`System ${this.id}: Cannot unblock access - alarm active!`);
      return;
    }

    this.accessBlocked = false;
    console.log(`System ${this.id}: Access unblocked.`);
  }

  // Custom method combining functionalities from different interfaces
  respondToBreakIn(): void {
    console.log(`System ${this.id}: Break-in attempt detected!`);
    this.startMonitoring();
    this.startAlarm();
    // Access is already blocked by startAlarm()
  }
}

// Using a class implementing multiple interfaces
const labSecuritySystem = new AdvancedSecuritySystem("SEC-LAB-01", 4);

// We can use methods from different interfaces
labSecuritySystem.startMonitoring();
console.log(labSecuritySystem.getMonitoringStatus());

// Checking access
console.log(labSecuritySystem.checkAccess(3)); // Denied - required level 4
console.log(labSecuritySystem.checkAccess(5)); // Access granted

// Reaction to break-in
labSecuritySystem.respondToBreakIn();

// Attempting to unblock access during alarm
labSecuritySystem.unblockAccess(); // Will not allow unlock

// Disabling alarm and unblocking
labSecuritySystem.disableAlarm();
labSecuritySystem.unblockAccess();

Implémenter des interfaces avec des conflits de noms

Que se passe-t-il lorsqu'on implémente deux interfaces ayant des propriétés du même nom ?

// Two interfaces with properties of the same name
interface SystemA {
  id: string;
  status: string;
  activate(): void;
}

interface SystemB {
  id: number; // Type conflict - string vs number
  status: string; // Same type, no conflict
  activate(code: string): boolean; // Signature conflict
}

// Attempting to implement both interfaces
// This implementation will cause a compilation error
/*
class ProblematicSituation implements SystemA, SystemB {
  id: string; // Cannot be both string and number
  status: string; // OK, same type in both interfaces

  // Attempting to implement both activate signatures
  activate(code?: string): boolean | void {
    if (code) {
      console.log(`Activation with code: ${code}`);
      return true;
    } else {
      console.log("Activation without code");
    }
  }
}
*/

// Correct implementation:
// We need to create a type compatible with both interfaces
interface CombinedSystem extends SystemA, SystemB {
  // Resolving the id conflict
  id: string & number; // Must be both string and number (impossible in practice)

  // Status without conflict
  status: string;

  // Resolving the method conflict
  activate(code?: string): boolean | void;
}

// In practice, it's often impossible to implement both interfaces simultaneously
// In such cases, it's better to modify one of the interfaces or
// create an adapter that delegates calls

Comment résoudre le problème des interfaces incompatibles :

// Better approach: Using composition instead of inheritance
class AccessSystem {
  private systemA: SystemAImplementation;
  private systemB: SystemBImplementation;

  constructor() {
    this.systemA = new SystemAImplementation("SYS-A");
    this.systemB = new SystemBImplementation(1001);
  }

  // Methods delegating to appropriate implementations
  activateA(): void {
    this.systemA.activate();
  }

  activateB(code: string): boolean {
    return this.systemB.activate(code);
  }

  getStatusA(): string {
    return this.systemA.status;
  }

  getStatusB(): string {
    return this.systemB.status;
  }
}

// Single interface implementations
class SystemAImplementation implements SystemA {
  id: string;
  status: string = "inactive";

  constructor(id: string) {
    this.id = id;
  }

  activate(): void {
    this.status = "active";
    console.log(`System A (${this.id}) activated`);
  }
}

class SystemBImplementation implements SystemB {
  id: number;
  status: string = "offline";

  constructor(id: number) {
    this.id = id;
  }

  activate(code: string): boolean {
    if (code === "secret-password") {
      this.status = "online";
      console.log(`System B (${this.id}) activated with code`);
      return true;
    }
    console.log(`System B (${this.id}) - incorrect activation code`);
    return false;
  }
}

Exemple pratique : système de gestion de Jurassic Park

Voici un exemple complet utilisant des interfaces pour créer un système de gestion de Jurassic Park :

// Interface for a basic manageable entity
interface InventoryItem {
  readonly id: string;
  name: string;
  category: string;
  additionDate: Date;
  lastUpdate: Date;
  status: "active" | "inactive" | "under_repair" | "retired";

  updateStatus(newStatus: "active" | "inactive" | "under_repair" | "retired"): void;
  getInfo(): Record<string, any>;
}

// Interface for trackable objects
interface Tracked {
  currentLocation: { x: number, y: number } | null;
  locationHistory: Array<{ time: Date, x: number, y: number }>;

  updateLocation(x: number, y: number): void;
  getLastLocation(): { time: Date, x: number, y: number } | null;
  getMovementRoute(fromTime: Date, toTime?: Date): Array<{ time: Date, x: number, y: number }>;
}

// Interface for monitorable objects
interface Monitored {
  monitoredParameters: Map<string, number | string | boolean>;
  measurementHistory: Array<{ time: Date, parameter: string, value: number | string | boolean }>;
  monitoringStatus: "enabled" | "disabled" | "limited";

  startMonitoring(): void;
  stopMonitoring(): void;
  addMeasurement(parameter: string, value: number | string | boolean): void;
  getRecentMeasurements(count?: number): Array<{ time: Date, parameter: string, value: number | string | boolean }>;
}

// Interface for objects requiring regular maintenance
interface Maintainable {
  requiredMaintenanceLevel: number; // 1-5
  lastMaintenance: Date | null;
  plannedMaintenance: Date | null;
  maintenanceHistory: Array<{ data: Date, description: string, contractor: string }>;

  scheduleMaintenance(data: Date): void;
  performMaintenance(description: string, contractor: string): void;
  checkMaintenanceStatus(): "required" | "scheduled" | "current";
}

// Interface for security systems
interface SecuritySystem {
  threatLevel: 1 | 2 | 3 | 4 | 5;
  securityZone: string;
  authorizedPersons: string[];

  raiseThreatLevel(): void;
  lowerThreatLevel(): void;
  checkPermissions(employeeId: string): boolean;
  respondToThreat(description: string): void;
}

// Implementation of a dinosaur tracking device
class TrackingDeviceT3000 implements InventoryItem, Tracked, Monitored, Maintainable {
  // InventoryItem (Inventory Item)
  readonly id: string;
  name: string;
  category: string = "Tracking Device";
  additionDate: Date;
  lastUpdate: Date;
  status: "active" | "inactive" | "under_repair" | "retired";

  // Tracked (Tracked)
  currentLocation: { x: number, y: number } | null = null;
  locationHistory: Array<{ time: Date, x: number, y: number }> = [];

  // Monitored (Monitored)
  monitoredParameters: Map<string, number | string | boolean> = new Map();
  measurementHistory: Array<{ time: Date, parameter: string, value: number | string | boolean }> = [];
  monitoringStatus: "enabled" | "disabled" | "limited" = "disabled";

  // Maintainable (Maintainable)
  requiredMaintenanceLevel: number = 3;
  lastMaintenance: Date | null = null;
  plannedMaintenance: Date | null = null;
  maintenanceHistory: Array<{ data: Date, description: string, contractor: string }> = [];

  // Custom properties
  private batteryLevel: number = 100; // in percent
  private assignedDinosaur: string | null = null;

  constructor(id: string, name: string) {
    this.id = id;
    this.name = name;
    this.additionDate = new Date();
    this.lastUpdate = new Date();
    this.status = "inactive";

    // Initializing monitoring parameters
    this.monitoredParameters.set("battery", this.batteryLevel);
    this.monitoredParameters.set("active", false);
    this.monitoredParameters.set("temperature", 25.0);
  }

  // Implementation of InventoryItem methods
  updateStatus(newStatus: "active" | "inactive" | "under_repair" | "retired"): void {
    this.status = newStatus;
    this.lastUpdate = new Date();
    console.log(`Device ${this.id}: Changed status to ${newStatus}`);
  }

  getInfo(): Record<string, any> {
    return {
      id: this.id,
      name: this.name,
      category: this.category,
      status: this.status,
      additionDate: this.additionDate,
      lastUpdate: this.lastUpdate,
      batteryLevel: this.batteryLevel,
      assignedDinosaur: this.assignedDinosaur
    };
  }

  // Implementation of Tracked methods
  updateLocation(x: number, y: number): void {
    const time = new Date();

    // Updating current location
    this.currentLocation = { x, y };

    // Adding to history
    this.locationHistory.push({ time, x, y });

    // Simulating battery drain
    this.reduceBattery(0.1);

    console.log(`Device ${this.id}: Updated location to [x: ${x}, y: ${y}]`);
  }

  getLastLocation(): { time: Date, x: number, y: number } | null {
    if (this.locationHistory.length === 0) {
      return null;
    }

    return this.locationHistory[this.locationHistory.length - 1];
  }

  getMovementRoute(fromTime: Date, toTime: Date = new Date()): Array<{ time: Date, x: number, y: number }> {
    return this.locationHistory.filter(loc =>
      loc.time >= fromTime && loc.time <= toTime
    );
  }

  // Implementation of Monitored methods
  startMonitoring(): void {
    if (this.monitoringStatus !== "enabled") {
      this.monitoringStatus = "enabled";
      console.log(`Device ${this.id}: Monitoring started`);

      // Simulating measurement when monitoring is enabled
      this.addMeasurement("active", true);
    }
  }

  stopMonitoring(): void {
    if (this.monitoringStatus !== "disabled") {
      this.monitoringStatus = "disabled";
      console.log(`Device ${this.id}: Monitoring stopped`);

      // Updating the activity parameter
      this.monitoredParameters.set("active", false);
      this.addMeasurement("active", false);
    }
  }

  addMeasurement(parameter: string, value: number | string | boolean): void {
    const time = new Date();

    // Updating the current parameter value
    this.monitoredParameters.set(parameter, value);

    // Adding to measurement history
    this.measurementHistory.push({ time, parameter, value });

    // Updating the last update time
    this.lastUpdate = time;

    console.log(`Device ${this.id}: Added measurement ${parameter} = ${value}`);
  }

  getRecentMeasurements(count: number = 10): Array<{ time: Date, parameter: string, value: number | string | boolean }> {
    // Returns the specified number of most recent measurements
    return this.measurementHistory.slice(-count);
  }

  // Implementation of Maintainable methods
  scheduleMaintenance(data: Date): void {
    this.plannedMaintenance = data;
    console.log(`Device ${this.id}: Scheduled maintenance for ${data.toLocaleDateString()}`);
  }

  performMaintenance(description: string, contractor: string): void {
    const date = new Date();

    // Adding to maintenance history
    this.maintenanceHistory.push({ date, description, contractor });

    // Updating the last maintenance date
    this.lastMaintenance = date;

    // Resetting planned maintenance
    this.plannedMaintenance = null;

    // Updating status and battery after maintenance
    this.updateStatus("active");
    this.batteryLevel = 100;
    this.monitoredParameters.set("battery", this.batteryLevel);
    this.addMeasurement("battery", this.batteryLevel);

    console.log(`Device ${this.id}: Maintenance performed by ${contractor}: ${description}`);
  }

  checkMaintenanceStatus(): "required" | "scheduled" | "current" {
    // No previous maintenance - required
    if (!this.lastMaintenance) {
      return "required";
    }

    // Planned maintenance in the future
    if (this.plannedMaintenance && this.plannedMaintenance > new Date()) {
      return "scheduled";
    }

    // Checking if more than 90 days have passed since the last maintenance
    const today = new Date();
    const differenceMilliseconds = today.getTime() - this.lastMaintenance.getTime();
    const differenceDays = differenceMilliseconds / (1000 * 60 * 60 * 24);

    if (differenceDays > 90 || this.batteryLevel < 20) {
      return "required";
    }

    return "current";
  }

  // Custom methods
  assignDinosaur(dinosaurId: string): void {
    this.assignedDinosaur = dinosaurId;
    this.addMeasurement("assignedDinosaur", dinosaurId);
    console.log(`Device ${this.id}: Assigned to dinosaur ${dinosaurId}`);
  }

  private reduceBattery(value: number): void {
    this.batteryLevel = Math.max(0, this.batteryLevel - value);
    this.monitoredParameters.set("battery", this.batteryLevel);

    // If battery is critically low - change status
    if (this.batteryLevel < 5 && this.status === "active") {
      this.updateStatus("inactive");
      console.log(`Device ${this.id}: Critical battery level! Device disabled.`);
    }
  }
}

// Implementation of dinosaur enclosure security system
class ElectricFence implements InventoryItem, SecuritySystem, Maintainable {
  // InventoryItem (Inventory Item)
  readonly id: string;
  name: string;
  category: string = "Fence Electric";
  additionDate: Date;
  lastUpdate: Date;
  status: "active" | "inactive" | "under_repair" | "retired";

  // SecuritySystem (Security System)
  threatLevel: 1 | 2 | 3 | 4 | 5 = 1;
  securityZone: string;
  authorizedPersons: string[] = [];

  // Maintainable (Maintainable)
  requiredMaintenanceLevel: number = 5; // Highest level - critical for security
  lastMaintenance: Date | null = null;
  plannedMaintenance: Date | null = null;
  maintenanceHistory: Array<{ data: Date, description: string, contractor: string }> = [];

  // Custom properties
  private voltage: number; // in volts
  private fenceLength: number; // in meters
  private motionSensors: boolean;

  constructor(
    id: string,
    name: string,
    securityZone: string,
    fenceLength: number,
    voltage: number = 10000,
    motionSensors: boolean = true
  ) {
    this.id = id;
    this.name = name;
    this.securityZone = securityZone;
    this.fenceLength = fenceLength;
    this.voltage = voltage;
    this.motionSensors = motionSensors;

    this.additionDate = new Date();
    this.lastUpdate = new Date();
    this.status = "inactive";

    // Adding system administrators as authorized personnel
    this.authorizedPersons.push("ADMIN-001", "SEC-CHIEF", "TECH-HEAD");
  }

  // Implementation of InventoryItem
  updateStatus(newStatus: "active" | "inactive" | "under_repair" | "retired"): void {
    // If switching from inactive to active
    if (this.status !== "active" && newStatus === "active") {
      // Check if maintenance is required
      if (this.checkMaintenanceStatus() === "required") {
        console.log(`Fence ${this.id}: WARNING - Activation without required maintenance!`);
      }
    }

    this.status = newStatus;
    this.lastUpdate = new Date();

    // Automatically adjust voltage based on status
    if (newStatus === "active") {
      console.log(`Fence ${this.id}: Activated with voltage ${this.voltage}V`);
    } else if (newStatus === "inactive" || newStatus === "under_repair") {
      this.voltage = 0;
      console.log(`Fence ${this.id}: Deactivated - voltage 0V`);
    }
  }

  getInfo(): Record<string, any> {
    return {
      id: this.id,
      name: this.name,
      category: this.category,
      status: this.status,
      securityZone: this.securityZone,
      fenceLength: this.fenceLength,
      voltage: this.voltage,
      motionSensors: this.motionSensors,
      threatLevel: this.threatLevel
    };
  }

  // Implementation of SecuritySystem
  raiseThreatLevel(): void {
    if (this.threatLevel < 5) {
      this.threatLevel = (this.threatLevel + 1) as 1 | 2 | 3 | 4 | 5;

      // Automatic voltage increase
      this.increaseVoltage(2000 * this.threatLevel);

      console.log(`Fence ${this.id}: Raised threat level to ${this.threatLevel}. New voltage: ${this.voltage}V`);
    } else {
      console.log(`Fence ${this.id}: Threat level already at maximum level 5`);
    }
  }

  lowerThreatLevel(): void {
    if (this.threatLevel > 1) {
      this.threatLevel = (this.threatLevel - 1) as 1 | 2 | 3 | 4 | 5;

      // Automatic voltage decrease (but still active)
      const newVoltage = 10000 + (2000 * (this.threatLevel - 1));
      this.voltage = newVoltage;

      console.log(`Fence ${this.id}: Lowered threat level to ${this.threatLevel}. New voltage: ${this.voltage}V`);
    } else {
      console.log(`Fence ${this.id}: Threat level already at minimum level 1`);
    }
  }

  checkPermissions(employeeId: string): boolean {
    return this.authorizedPersons.includes(employeeId);
  }

  respondToThreat(description: string): void {
    console.log(`Fence ${this.id}: ALERT! ${description}`);

    // Maximum threat level
    this.threatLevel = 5;

    // Maximum voltage
    this.voltage = 30000;

    console.log(`Fence ${this.id}: Threat level 5. Maximum voltage: ${this.voltage}V`);
  }

  // Implementation of Maintainable
  scheduleMaintenance(data: Date): void {
    this.plannedMaintenance = data;
    console.log(`Fence ${this.id}: Scheduled maintenance for ${date.toLocaleDateString()}`);
  }

  performMaintenance(description: string, contractor: string): void {
    const date = new Date();

    // Safety measure - temporary fence deactivation during maintenance
    const previousStatus = this.status;
    this.updateStatus("under_repair");

    // Add to maintenance history
    this.maintenanceHistory.push({ date, description, contractor });

    // Update last maintenance date
    this.lastMaintenance = date;

    // Reset planned maintenance
    this.plannedMaintenance = null;

    console.log(`Fence ${this.id}: Maintenance performed by ${contractor}: ${description}`);

    // Restoring previous status
    this.updateStatus(previousStatus);
  }

  checkMaintenanceStatus(): "required" | "scheduled" | "current" {
    // No prior maintenance - required
    if (!this.lastMaintenance) {
      return "required";
    }

    // Maintenance scheduled in the future
    if (this.plannedMaintenance && this.plannedMaintenance > new Date()) {
      return "scheduled";
    }

    // Checking if more than 30 days have passed since last maintenance (shorter period for fences)
    const today = new Date();
    const differenceMilliseconds = today.getTime() - this.lastMaintenance.getTime();
    const differenceDays = differenceMilliseconds / (1000 * 60 * 60 * 24);

    if (differenceDays > 30) {
      return "required";
    }

    return "current";
  }

  // Custom methods
  addAuthorizedPerson(employeeId: string): void {
    if (!this.authorizedPersons.includes(employeeId)) {
      this.authorizedPersons.push(employeeId);
      console.log(`Enclosure ${this.id}: Added permissions for employee ${employeeId}`);
    }
  }

  removeAuthorizedPerson(employeeId: string): void {
    const index = this.authorizedPersons.indexOf(employeeId);
    if (index !== -1) {
      this.authorizedPersons.splice(index, 1);
      console.log(`Fence ${this.id}: Removed permissions for employee ${employeeId}`);
    }
  }

  increaseVoltage(value: number): void {
    if (this.status !== "active") {
      console.log(`Fence ${this.id}: Cannot change voltage - fence is not active`);
      return;
    }

    this.voltage += value;
    console.log(`Fence ${this.id}: Increased voltage to ${this.voltage}V`);
  }

  decreaseVoltage(value: number): void {
    if (this.status !== "active") {
      console.log(`Fence ${this.id}: Cannot change voltage - fence is not active`);
      return;
    }

    this.voltage = Math.max(0, this.voltage - value);
    console.log(`Fence ${this.id}: Decreased voltage to ${this.voltage}V`);
  }
}

// Demonstrating the use of our implementations
function demonstrateParkSystem() {
  console.log("=== JURASSIC PARK MANAGEMENT SYSTEM DEMONSTRATION ===");

  // Creating a tracking device
  console.log("\n--- Initializing tracking device ---");
  const trackingDevice = new TrackingDeviceT3000("TRACK-001", "T-Rex Tracker #1");
  trackingDevice.updateStatus("active");
  trackingDevice.startMonitoring();
  trackingDevice.assignDinosaur("TREX-001");

  // Simulating location tracking
  trackingDevice.updateLocation(135.42, 86.21);
  trackingDevice.updateLocation(135.50, 86.35);
  trackingDevice.updateLocation(135.62, 86.40);

  // Creating a fence
  console.log("\n--- Fence initialization ---");
  const fence = new ElectricFence(
    "FENCE-002",
    "Fence enclosure T-Rex",
    "T-REX-A",
    1200, // 1200 meters long
    15000, // 15000V
    true // from motion sensors
  );

  // Adding permissions for an employee
  fence.addAuthorizedPerson("EMP-047"); // Owen Grady

  // Activating the fence
  fence.updateStatus("active");

  // Performing device maintenance
  console.log("\n--- Device maintenance ---");
  trackingDevice.scheduleMaintenance(new Date("2023-06-15"));
  trackingDevice.performMaintenance("Battery replacement and GPS calibration", "Tech Ivan");

  // Simulating an alarm
  console.log("\n--- Simulation incident ---");
  console.log("T-Rex is trying to break through the fence!");

  // Tracking device registers rapid movement
  trackingDevice.updateLocation(135.90, 86.70);
  trackingDevice.updateLocation(136.10, 86.90);
  trackingDevice.addMeasurement("acceleration", 12.5);

  // Fence responds to threat
  fence.respondToThreat("T-Rex escape attempt detected");

  // Status checks after incident
  console.log("\n--- Post-incident report ---");
  console.log("Last dinosaur location:", trackingDevice.getLastLocation());
  console.log("Status fence:", fence.getInfo());

  // Returning to normal mode
  console.log("\n--- Normalization situation ---");
  fence.lowerThreatLevel();
  fence.lowerThreatLevel();

  console.log("\n=== END DEMONSTRATION ===");
}

// Running the demonstration
demonstrateParkSystem();

Résumé

Dans cet exercice, nous avons découvert les interfaces TypeScript - un outil puissant pour définir des contrats et créer des structures cohérentes dans le code.

Caractéristiques clés des interfaces :

  1. Définir la forme des objets - préciser quelles propriétés et méthodes les objets d'un type donné doivent avoir
  2. Prise en charge du polymorphisme - différentes classes peuvent implémenter la même interface de différentes manières
  3. Couplage faible - se concentrer sur ce que font les objets, et non sur la façon dont ils sont implémentés
  4. Flexibilité - propriétés optionnelles, en lecture seule, signatures d'index, etc.
  5. Extensibilité - les interfaces peuvent hériter d'autres interfaces

Comme le résumerait Claire Dearing : « À Jurassic Park, comme dans une bonne architecture logicielle, chacun a son rôle et ses responsabilités. Les interfaces nous permettent de définir clairement ces rôles, en garantissant que tous les systèmes coopèrent bien - sans surprises. Et crois-moi, les surprises dans un parc rempli de dinosaures sont la dernière chose dont nous avons besoin. »

Code de cette leçon : index.ts
// Implémentation des interfaces - Parc Jurassique
console.log("=== IMPLÉMENTATION DES INTERFACES ===\n");

// ===========================================
// 1. Définition des interfaces
// ===========================================

interface ITrackable {
  readonly trackingId: string;
  location: { x: number; y: number };
  getLocation(): string;
  updateLocation(x: number, y: number): void;
}

interface IFeedable {
  diet: "carnivore" | "herbivore" | "omnivore";
  lastFedAt: Date;
  feed(food: string): string;
  isHungry(): boolean;
}

interface IContainable {
  enclosureId: string;
  isContained: boolean;
  checkContainment(): string;
}

// ===========================================
// 2. Classe implémentant plusieurs interfaces
// ===========================================

class ParkDinosaur implements ITrackable, IFeedable, IContainable {
  readonly trackingId: string;
  location: { x: number; y: number };
  diet: "carnivore" | "herbivore" | "omnivore";
  lastFedAt: Date;
  enclosureId: string;
  isContained: boolean;
  name: string;

  constructor(
    name: string,
    diet: "carnivore" | "herbivore" | "omnivore",
    enclosureId: string
  ) {
    this.name = name;
    this.trackingId = `TRK-${Math.random().toString(36).substring(2, 8).toUpperCase()}`;
    this.location = { x: 0, y: 0 };
    this.diet = diet;
    this.lastFedAt = new Date();
    this.enclosureId = enclosureId;
    this.isContained = true;
  }

  // ITrackable
  getLocation(): string {
    return `(${this.location.x}, ${this.location.y})`;
  }

  updateLocation(x: number, y: number): void {
    this.location = { x, y };
    console.log(`  ${this.name} déplacé vers ${this.getLocation()}`);
  }

  // IFeedable
  feed(food: string): string {
    this.lastFedAt = new Date();
    return `${this.name} a mangé: ${food}`;
  }

  isHungry(): boolean {
    const hoursSinceFed = (Date.now() - this.lastFedAt.getTime()) / 3600000;
    return hoursSinceFed > 4;
  }

  // IContainable
  checkContainment(): string {
    return this.isContained
      ? `${this.name} est en sécurité dans l'enclos ${this.enclosureId}`
      : `ALARM! ${this.name} s'est échappé de l'enclos ${this.enclosureId}!`;
  }
}

// ===========================================
// 3. Fonctions opérant sur les interfaces
// ===========================================

function trackEntity(entity: ITrackable): void {
  console.log(`Suivi: ${entity.trackingId} à la position ${entity.getLocation()}`);
}

function feedEntity(entity: IFeedable): void {
  console.log(`Diet: ${entity.diet}`);
  console.log(`Affamé: ${entity.isHungry() ? "OUI" : "NON"}`);
}

function checkSafety(entities: IContainable[]): void {
  console.log("\n--- Rapport de sécurité ---");
  entities.forEach(e => console.log(e.checkContainment()));
}

// ===========================================
// Test
// ===========================================

const velociraptor = new ParkDinosaur("Blue", "carnivore", "ENC-A7");
const brachio = new ParkDinosaur("Patty", "herbivore", "ENC-B3");

console.log("--- Suivi ---");
trackEntity(velociraptor);
velociraptor.updateLocation(45, 120);
trackEntity(velociraptor);

console.log("\n--- Alimentation ---");
console.log(velociraptor.feed("Chèvre"));
console.log(brachio.feed("Feuilles de palmier"));
feedEntity(brachio);

brachio.isContained = false; // Évasion !
checkSafety([velociraptor, brachio]);

console.log("\nInterfaces enable polymorphism and loose coupling!");

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Que fait le mot-clé implements en TypeScript ?

  2. 2. Comment définit-on une interface générique en TypeScript ?

Tâches pratiques dans le jeu

  • Éditeur de code

    Implémente les interfaces ITrackable et IFeedable pour les entités du parc

  • Tri horizontal

    Range les éléments d'une interface générique :

  1. QuestionImplémentation d'interface
  2. Exercice de codeImplémenter des interfaces
  3. Remets dans l'ordreSyntaxe d'une interface générique
  4. QuestionInterface générique

Articles utiles