Cours JavaScript et TypeScript · Module 6: Bases de TypeScript

Étendre les interfaces

18 min de lecture ·
Dans cette leçon9

Bienvenue de nouveau à Jurassic Park ! Aujourd'hui, le Dr Henry Wu va nous guider à travers une technique avancée de TypeScript qui constitue le fondement de la construction de systèmes évolutifs et flexibles : l'extension d'interfaces. Tout comme les scientifiques du parc enrichissent les traits de base des dinosaures avec de nouvelles propriétés génétiques, en TypeScript on peut étendre des interfaces de base avec de nouvelles fonctionnalités.

Mécanisme de base de l'extension d'interfaces

Étendre une interface en TypeScript permet de créer de nouvelles interfaces à partir de celles qui existent déjà, en y ajoutant de nouvelles propriétés ou méthodes. On utilise pour cela le mot-clé extends :

// Base interface for all creatures in the park
interface Creature {
  id: string;
  name: string;
  species: string;
  age: number;
  weight: number;
}

// Extending the base interface with additional properties for dinosaurs
interface Dinosaur extends Creature {
  originEra: string; // e.g. "Jurassic", "Cretaceous"
  diet: "herbivore" | "carnivore" | "omnivore";
  dangerous: boolean;
}

// Now the Dinosaur interface contains all fields from Creature plus its own
const trex: Dinosaur = {
  id: "TREX-01",
  name: "Rex",
  species: "Tyrannosaurus Rex",
  age: 7,
  weight: 7000,
  originEra: "Cretaceous",
  diet: "carnivore",
  dangerous: true
};

Étendre plusieurs interfaces

Une interface peut étendre simultanément plusieurs autres interfaces, ce qui permet de composer des types complexes à partir de parties plus petites et spécialisées, un peu comme les scientifiques combinent l'ADN de différentes espèces pour créer des hybrides :

// Interface defining predator abilities
interface PredatorAbilities {
  biteForce: number; // in PSI
  runSpeed: number; // in km/h
  huntingStyle: "ambush" | "chase" | "pack";
}

// Interface defining aquatic animal traits
interface AquaticAnimal {
  swimmingAbility: number; // 1 to 10
  maxDepth: number; // in meters
  saltWaterResistance: boolean;
}

// Interface for a marine predator combining both of the above interfaces
interface MarinePredator extends PredatorAbilities, AquaticAnimal {
  scientificName: string;
}

// Creating a dinosaur that is a marine predator
const mosasaurus: MarinePredator & Dinosaur = {
  // Properties from Creature
  id: "MOSA-01",
  name: "Mosa",
  species: "Mosasaurus",
  age: 15,
  weight: 15000,

  // Properties from Dinosaur
  originEra: "Cretaceous",
  diet: "carnivore",
  dangerous: true,

  // Properties from PredatorAbilities
  biteForce: 18000,
  runSpeed: 0, // doesn't run, swims
  huntingStyle: "ambush",

  // Properties from AquaticAnimal
  swimmingAbility: 9,
  maxDepth: 500,
  saltWaterResistance: true,

  // Properties from MarinePredator
  scientificName: "Mosasaurus hoffmannii"
};

// Demonstration of accessing different properties
function analyzeMarinePredator(dino: MarinePredator & Dinosaur): void {
  console.log(`Analyzing: ${dino.name} (${dino.species})`);
  console.log(`Bite force: ${dino.biteForce} PSI`);
  console.log(`Can dive to depth: ${dino.maxDepth} meters`);
  console.log(`Visitor threat: ${dino.dangerous ? "HIGH" : "LOW"}`);
}

analyzeMarinePredator(mosasaurus);

Extension d'interfaces vs héritage de classes

Étendre une interface ressemble à l'héritage de classes, mais présente plusieurs différences clés. À Jurassic Park, on pourrait comparer cela à la différence entre la « description d'un dinosaure idéal » (l'interface) et un « dinosaure réel » (la classe) :

// Interface for security systems
interface SecuritySystem {
  name: string;
  securityLevel: number;
  isActive: boolean;

  activate(): void;
  deactivate(): void;
  test(): boolean;
}

// Class implementing the interface
class ElectronicFence implements SecuritySystem {
  name: string;
  securityLevel: number;
  isActive: boolean;
  voltage: number; // additional property specific to this class

  constructor(name: string, securityLevel: number, voltage: number) {
    this.name = name;
    this.securityLevel = securityLevel;
    this.isActive = false;
    this.voltage = voltage;
  }

  activate(): void {
    this.isActive = true;
    console.log(`System ${this.name} activated with voltage ${this.voltage}V`);
  }

  deactivate(): void {
    this.isActive = false;
    console.log(`System ${this.name} deactivated`);
  }

  test(): boolean {
    console.log(`Testing system ${this.name}...`);
    return Math.random() > 0.1; // 90% chance of successful test
  }

  // Method specific to this class
  increaseVoltage(by: number): void {
    this.voltage += by;
    console.log(`Voltage increased to ${this.voltage}V`);
  }
}

// Extended version of SecuritySystem for more advanced systems
interface AdvancedSecuritySystem extends SecuritySystem {
  backupPower: boolean;
  videoMonitoring: boolean;
  alarmNotifications: boolean;

  runSecurityProcedure(threatLevel: number): void;
}

// Class implementing the extended interface
class IntegratedSecuritySystem implements AdvancedSecuritySystem {
  name: string;
  securityLevel: number;
  isActive: boolean;
  backupPower: boolean;
  videoMonitoring: boolean;
  alarmNotifications: boolean;

  constructor(name: string, securityLevel: number) {
    this.name = name;
    this.securityLevel = securityLevel;
    this.isActive = false;
    this.backupPower = true;
    this.videoMonitoring = true;
    this.alarmNotifications = true;
  }

  activate(): void {
    this.isActive = true;
    console.log(`Integrated system ${this.name} activated`);
  }

  deactivate(): void {
    this.isActive = false;
    console.log(`Integrated system ${this.name} deactivated`);
  }

  test(): boolean {
    console.log(`Testing integrated system ${this.name}...`);
    const powerTest = Math.random() > 0.05;
    const monitoringTest = Math.random() > 0.05;
    const notificationsTest = Math.random() > 0.05;

    return powerTest && monitoringTest && notificationsTest;
  }

  runSecurityProcedure(threatLevel: number): void {
    console.log(`Activating security procedure level ${threatLevel} for system ${this.name}`);
    this.activate();

    if (threatLevel >= 4) {
      console.log("WARNING: High threat level! Activating all security measures!");
    }
  }
}

// Usage demonstration
const trexFence = new ElectronicFence("T-Rex Enclosure", 5, 10000);
trexFence.activate();
trexFence.increaseVoltage(2000);

const integratedParkSystem = new IntegratedSecuritySystem("Main System", 5);
integratedParkSystem.runSecurityProcedure(4);

Étendre et implémenter des interfaces generic

Les interfaces generic sont particulièrement puissantes pour modéliser des systèmes complexes, comme la surveillance de différents types de données dans le parc :

// Generic interface for a monitoring system
interface MonitoringSystemType<T> {
  identifier: string;
  dataType: string;
  currentData: T;
  historicalData: T[];

  save(data: T): void;
  getLatest(n: number): T[];
  analyzeTrend(): string;
}

// Sample data type for environmental monitoring
interface EnvironmentalData {
  temperature: number;
  humidity: number;
  co2Level: number;
  sunExposure: number;
  pressure: number;
  measurementTime: Date;
}

// Implementation of monitoring system for a specific data type
class EnvironmentalMonitoring implements MonitoringSystemType<EnvironmentalData> {
  identifier: string;
  dataType: string;
  currentData: EnvironmentalData;
  historicalData: EnvironmentalData[];

  constructor(identifier: string) {
    this.identifier = identifier;
    this.dataType = "environmental";
    this.currentData = {
      temperature: 0,
      humidity: 0,
      co2Level: 0,
      sunExposure: 0,
      pressure: 0,
      measurementTime: new Date()
    };
    this.historicalData = [];
  }

  save(data: EnvironmentalData): void {
    this.currentData = data;
    this.historicalData.push(data);
    console.log(`Saved new data for monitor ${this.identifier} at ${data.measurementTime.toISOString()}`);
  }

  getLatest(n: number): EnvironmentalData[] {
    return this.historicalData.slice(-n);
  }

  analyzeTrend(): string {
    if (this.historicalData.length < 2) {
      return "Not enough data to analyze trend";
    }

    const latest = this.historicalData[this.historicalData.length - 1];
    const previous = this.historicalData[this.historicalData.length - 2];

    let trends = [];

    if (latest.temperature > previous.temperature) {
      trends.push("Temperature: RISING");
    } else if (latest.temperature < previous.temperature) {
      trends.push("Temperature: FALLING");
    } else {
      trends.push("Temperature: STABLE");
    }

    if (latest.humidity > previous.humidity) {
      trends.push("Humidity: RISING");
    } else if (latest.humidity < previous.humidity) {
      trends.push("Humidity: FALLING");
    } else {
      trends.push("Humidity: STABLE");
    }

    return trends.join(", ");
  }

  // Method specific to environmental monitoring
  temperatureWarning(): boolean {
    return this.currentData.temperature > 35 || this.currentData.temperature < 15;
  }
}

// Extending the base interface with specific functions for dinosaur monitoring
interface DinosaurMonitoringSystem<T> extends MonitoringSystemType<T> {
  dinosaurId: string;
  species: string;
  alarmThresholds: Partial<T>;

  checkAlarmThresholds(): boolean;
  sendAlertIfNeeded(): void;
}

// Data type for dinosaur health monitoring
interface DinosaurHealthData {
  bodyTemperature: number;
  heartRate: number;
  bloodPressure: [number, number]; // [systolic, diastolic]
  stressLevel: number; // 1-10
  activityLevel: number; // 1-10
  measurementTime: Date;
}

// Implementation of specific monitoring system for dinosaurs
class DinosaurHealthMonitoring implements DinosaurMonitoringSystem<DinosaurHealthData> {
  identifier: string;
  dataType: string;
  currentData: DinosaurHealthData;
  historicalData: DinosaurHealthData[];
  dinosaurId: string;
  species: string;
  alarmThresholds: Partial<DinosaurHealthData>;

  constructor(identifier: string, dinosaurId: string, species: string) {
    this.identifier = identifier;
    this.dataType = "health";
    this.currentData = {
      bodyTemperature: 0,
      heartRate: 0,
      bloodPressure: [0, 0],
      stressLevel: 0,
      activityLevel: 0,
      measurementTime: new Date()
    };
    this.historicalData = [];
    this.dinosaurId = dinosaurId;
    this.species = species;

    // Setting alarm thresholds based on species
    if (species === "Tyrannosaurus") {
      this.alarmThresholds = {
        bodyTemperature: 39, // Above this temperature - alarm
        heartRate: 95, // Above this heart rate - alarm
        stressLevel: 7 // Above this stress level - alarm
      };
    } else if (species === "Velociraptor") {
      this.alarmThresholds = {
        bodyTemperature: 40,
        heartRate: 120,
        stressLevel: 8
      };
    } else {
      // Default thresholds for other species
      this.alarmThresholds = {
        bodyTemperature: 38,
        heartRate: 100,
        stressLevel: 7
      };
    }
  }

  save(data: DinosaurHealthData): void {
    this.currentData = data;
    this.historicalData.push(data);
    console.log(`Saved new health data for dinosaur ${this.dinosaurId} (${this.species})`);

    // Check if values exceed thresholds
    this.sendAlertIfNeeded();
  }

  getLatest(n: number): DinosaurHealthData[] {
    return this.historicalData.slice(-n);
  }

  analyzeTrend(): string {
    if (this.historicalData.length < 2) {
      return "Not enough data to analyze trend";
    }

    return "Health trend analysis (sample implementation)";
  }

  checkAlarmThresholds(): boolean {
    let thresholdExceeded = false;

    if (this.alarmThresholds.bodyTemperature &&
        this.currentData.bodyTemperature > this.alarmThresholds.bodyTemperature) {
      console.log(`ALARM: Dinosaur ${this.dinosaurId} body temperature exceeds threshold!`);
      thresholdExceeded = true;
    }

    if (this.alarmThresholds.heartRate &&
        this.currentData.heartRate > this.alarmThresholds.heartRate) {
      console.log(`ALARM: Dinosaur ${this.dinosaurId} heart rate exceeds threshold!`);
      thresholdExceeded = true;
    }

    if (this.alarmThresholds.stressLevel &&
        this.currentData.stressLevel > this.alarmThresholds.stressLevel) {
      console.log(`ALARM: Dinosaur ${this.dinosaurId} stress level exceeds threshold!`);
      thresholdExceeded = true;
    }

    return thresholdExceeded;
  }

  sendAlertIfNeeded(): void {
    if (this.checkAlarmThresholds()) {
      console.log(`Sending alert to veterinary team for dinosaur ${this.dinosaurId}!`);
    }
  }

  // Method specific to dinosaur health monitoring
  recommendIntervention(): string {
    let recommendations = [];

    if (this.currentData.bodyTemperature > this.alarmThresholds.bodyTemperature!) {
      recommendations.push("Lower body temperature");
    }

    if (this.currentData.stressLevel > this.alarmThresholds.stressLevel!) {
      recommendations.push("Administer sedatives");
    }

    if (this.currentData.activityLevel < 3) {
      recommendations.push("Check energy level and possibly increase food portion");
    }

    return recommendations.length > 0
      ? `Recommended actions: ${recommendations.join(", ")}`
      : "No recommendations - parameters within normal range";
  }
}

// Example usage
const monitorPaddockTRex = new EnvironmentalMonitoring("ENV-TREX-01");
monitorPaddockTRex.save({
  temperature: 28.5,
  humidity: 75,
  co2Level: 420,
  sunExposure: 80,
  pressure: 1013,
  measurementTime: new Date()
});

const monitorRexy = new DinosaurHealthMonitoring("HEALTH-TREX-01", "TREX-01", "Tyrannosaurus");
monitorRexy.save({
  bodyTemperature: 38.2,
  heartRate: 72,
  bloodPressure: [135, 85],
  stressLevel: 3,
  activityLevel: 4,
  measurementTime: new Date()
});

// Simulating a health problem
monitorRexy.save({
  bodyTemperature: 40.1, // Fever!
  heartRate: 98, // Elevated heart rate
  bloodPressure: [155, 95], // High blood pressure
  stressLevel: 8, // High stress level
  activityLevel: 2, // Low activity
  measurementTime: new Date()
});

console.log(monitorRexy.recommendIntervention());

La fusion des déclarations d'interfaces

L'une des particularités de TypeScript est la possibilité de fusionner plusieurs déclarations d'une même interface, un peu comme les scientifiques de Jurassic Park mettent à jour leurs protocoles à mesure qu'ils obtiennent de nouvelles informations :

// Initial definition of the security protocol
interface SecurityProtocolType {
  id: string;
  name: string;
  threatLevel: 1 | 2 | 3 | 4 | 5;
  evacuationProcedure: string;
}

// Later extension of the same interface with additional information
interface SecurityProtocolType {
  responsibleStaff: string[];
  responseTime: number; // in minutes
}

// Even later extension with communication procedures
interface SecurityProtocolType {
  communicationChannels: string[];
  alarmMessage: string;
}

// Now SecurityProtocolType has all fields from all three declarations
const protocolAlpha: SecurityProtocolType = {
  id: "PROTO-ALFA",
  name: "Protocol Alpha - Predator Escape",
  threatLevel: 5,
  evacuationProcedure: "Immediate evacuation of all public areas to safety bunkers",
  responsibleStaff: ["Security manager", "Park manager", "Head trainer"],
  responseTime: 5,
  communicationChannels: ["Radio", "PA System", "Audible alarm", "SMS notifications"],
  alarmMessage: "ATTENTION! PROTOCOL ALPHA! This is not a drill. Please immediately proceed to the nearest shelter."
};

// Function to display the protocol
function displayProtocol(protocol: SecurityProtocolType): void {
  console.log(`=== ${protocol.name.toUpperCase()} ===`);
  console.log(`ID: ${protocol.id}`);
  console.log(`Threat level: ${protocol.threatLevel}`);
  console.log(`Response time: ${protocol.responseTime} minutes`);
  console.log(`\nEvacuation procedure:\n${protocol.evacuationProcedure}`);
  console.log(`\nResponsible personnel:`);
  protocol.responsibleStaff.forEach(person => console.log(`- ${person}`));
  console.log(`\nCommunication channels: ${protocol.communicationChannels.join(", ")}`);
  console.log(`\nAlarm message: "${protocol.alarmMessage}"`);
}

displayProtocol(protocolAlpha);

Compatibilité structurelle des interfaces

TypeScript utilise la compatibilité structurelle : cela signifie que des types sont compatibles s'ils ont la même structure, peu importe leur nom. C'est comme à Jurassic Park : si un dinosaure se comporte comme un T-Rex et ressemble à un T-Rex, du point de vue du système de sécurité, il doit être traité comme un T-Rex :

// Definition of a predatory dinosaur interface
interface PredatoryDinosaur {
  id: string;
  name: string;
  biteForce: number;
  runSpeed: number;
  aggressionLevel: number;
}

// Completely separate definition, with no formal relationship to the above interface
interface DangerousCreature {
  id: string;
  name: string;
  biteForce: number;
  runSpeed: number;
  aggressionLevel: number;
  // Additional field that does not interfere with compatibility
  origin?: string;
}

function assessThreat(dino: PredatoryDinosaur): number {
  return (dino.biteForce / 1000) + (dino.runSpeed / 10) + dino.aggressionLevel;
}

// Creating an object conforming to DangerousCreature
const indominus: DangerousCreature = {
  id: "IND-01",
  name: "Indominus Rex",
  biteForce: 15000,
  runSpeed: 48,
  aggressionLevel: 10,
  origin: "Laboratory"
};

// Even though indominus is of type DangerousCreature, it can be used where
// PredatoryDinosaur is expected, thanks to structural compatibility
const threatLevel = assessThreat(indominus);
console.log(`Threat level for ${indominus.name}: ${threatLevel}`);

// Function expecting an object conforming to DangerousCreature
function describeThreat(creature: DangerousCreature): string {
  let description = `${creature.name} is an extremely dangerous creature.\n`;
  description += `Bite force: ${creature.biteForce} PSI\n`;
  description += `Running speed: ${creature.runSpeed} km/h\n`;
  description += `Aggression level: ${creature.aggressionLevel}/10\n`;

  if (creature.origin) {
    description += `Created in: ${creature.origin}`;
  }

  return description;
}

// Creating an object conforming to PredatoryDinosaur
const velociraptor: PredatoryDinosaur = {
  id: "VEL-01",
  name: "Blue",
  biteForce: 4000,
  runSpeed: 65,
  aggressionLevel: 7
};

// We can use an object of type PredatoryDinosaur in a function expecting DangerousCreature
// It works because velociraptor has all the required properties
const raptorDescription = describeThreat(velociraptor);
console.log(raptorDescription);

Interfaces vs types abstraits

Comparons les interfaces avec les types abstraits (classes abstraites) dans le contexte de Jurassic Park :

// Interface for security systems
interface SecuritySystemInterface {
  name: string;
  activate(): void;
  deactivate(): void;
  test(): boolean;
}

// Abstract class for security systems
abstract class SecuritySystemAbstractClass {
  constructor(public name: string, protected securityLevel: number) {}

  abstract activate(): void;
  abstract deactivate(): void;

  // Shared implementation for all derived classes
  test(): boolean {
    console.log(`Testing system ${this.name}...`);
    return Math.random() > 0.1; // 90% chance of success
  }

  // Method available to all derived classes
  getLevel(): number {
    return this.securityLevel;
  }
}

// Interface implementation
class MotionScanners implements SecuritySystemInterface {
  constructor(public name: string) {}

  activate(): void {
    console.log(`Motion scanners ${this.name} activated`);
  }

  deactivate(): void {
    console.log(`Motion scanners ${this.name} deactivated`);
  }

  test(): boolean {
    console.log(`Testing motion scanners ${this.name}...`);
    return true;
  }
}

// Extending the abstract class
class ElectricFence extends SecuritySystemAbstractClass {
  private voltage: number;

  constructor(name: string, securityLevel: number, voltage: number) {
    super(name, securityLevel);
    this.voltage = voltage;
  }

  activate(): void {
    console.log(`Electric fence ${this.name} activated with voltage ${this.voltage}V`);
  }

  deactivate(): void {
    console.log(`Electric fence ${this.name} deactivated`);
  }

  increaseVoltage(o: number): void {
    this.voltage += o;
    console.log(`Voltage of fence ${this.name} increased to ${this.voltage}V`);
  }
}

// Using both approaches
const scanners = new MotionScanners("T-Rex Zone");
scanners.activate();
scanners.test();

const fence = new ElectricFence("Eastern paddock", 4, 10000);
fence.activate();
fence.increaseVoltage(2000);
console.log(`Fence security level: ${fence.getLevel()}`);

Différences clés :

CaractéristiqueInterfaceClasse abstraite
ImplémentationDéfinition uniquement, aucune implémentationPeut contenir des implémentations de méthodes
HéritageUne classe peut implémenter plusieurs interfacesUne classe ne peut hériter que d'une seule classe abstraite
ConstructeurPas de constructeurPeut avoir un constructeur
Code au runtimeLes interfaces ne génèrent aucun code JavaScriptLes classes abstraites génèrent du code JavaScript
Modificateurs d'accèsNe peut pas utiliser de modificateurs (private, protected)Peut utiliser des modificateurs d'accès
UsageDéfinir un contratDéfinir des fonctionnalités de base avec une implémentation partielle

Application pratique de l'extension d'interfaces

Voyons maintenant un exemple complet illustrant comment l'extension d'interfaces peut être utilisée dans le système de gestion de Jurassic Park :

// Base interface for all entities in the park
interface JurassicParkBase {
  id: string;
  name: string;
  dateAdded: Date;
  lastUpdated: Date;
}

// Extension for living creatures
interface ParkLivingCreatures extends JurassicParkBase {
  age: number;
  gender: "male" | "female";
  healthStatus: "excellent" | "good" | "needs attention" | "sick" | "critical";
  healthHistory: {
    date: Date;
    description: string;
    procedure?: string;
  }[];
}

// Extension for dinosaurs
interface ParkDinosaur extends ParkLivingCreatures {
  species: string;
  originEra: string;
  diet: "herbivore" | "carnivore" | "omnivore";
  dangerLevel: 1 | 2 | 3 | 4 | 5;
  location: string; // Enclosure ID
  traits: {
    height: number;
    length: number;
    weight: number;
    maxSpeed: number;
    biteForce?: number; // Only for predators
  };
}

// Extension for employees
interface ParkEmployee extends ParkLivingCreatures {
  firstName: string;
  lastName: string;
  position: string;
  accessLevel: 1 | 2 | 3 | 4 | 5;
  departments: string[];
  address: {
    street: string;
    city: string;
    postalCode: string;
    country: string;
  };
  contact: {
    phone: string;
    email: string;
  };
}

// Interface for park locations
interface ParkLocation extends JurassicParkBase {
  type: "enclosure" | "building" | "attraction" | "laboratory" | "public zone";
  coordinates: {
    width: number;
    length: number;
  };
  area: number; // in square meters
  capacity: number;
  accessLevel: 1 | 2 | 3 | 4 | 5;
  securitySystems: string[]; // List of security system IDs
  status: "active" | "inactive" | "under maintenance" | "under construction";
}

// Interface for dinosaur enclosures
interface DinosaurEnclosure extends ParkLocation {
  residents: string[]; // List of dinosaur IDs
  environmentType: "forest" | "savanna" | "swamp" | "mountains" | "coast" | "water";
  specialRequirements?: string[];
  traits: {
    fenceHeight: number;
    fenceVoltage?: number; // For predators
    scannersCount: number;
    cameraCount: number;
  };
}

// Interface for laboratories
interface ParkLaboratory extends ParkLocation {
  specializations: "genetics" | "behavioral" | "veterinary" | "microbiology";
  equipment: string[];
  staff: string[]; // List of employee IDs
  researchProjects: {
    id: string;
    name: string;
    start: Date;
    end?: Date;
    status: "planned" | "in progress" | "completed" | "suspended";
  }[];
}

// Park management system
class JurassicParkSystem {
  private dinosaurs: Map<string, ParkDinosaur> = new Map();
  private employees: Map<string, ParkEmployee> = new Map();
  private locations: Map<string, ParkLocation> = new Map();
  private laboratories: Map<string, ParkLaboratory> = new Map();
  private enclosures: Map<string, DinosaurEnclosure> = new Map();

  // Methods for dinosaurs
  addDinosaur(dino: ParkDinosaur): void {
    this.dinosaurs.set(dino.id, dino);
    console.log(`Added dinosaur: ${dino.name} (${dino.species})`);

    // Update enclosure
    if (dino.location && this.enclosures.has(dino.location)) {
      const enclosure = this.enclosures.get(dino.location)!;
      enclosure.residents.push(dino.id);
      this.enclosures.set(enclosure.id, enclosure);
    }
  }

  updateDinosaurHealthStatus(id: string, newStatus: ParkDinosaur["healthStatus"], description: string): void {
    if (!this.dinosaurs.has(id)) {
      console.error(`Dinosaur with ID ${id} does not exist`);
      return;
    }

    const dino = this.dinosaurs.get(id)!;
    const oldStatus = dino.healthStatus;
    dino.healthStatus = newStatus;
    dino.lastUpdated = new Date();

    // Add entry to health history
    dino.healthHistory.push({
      date: new Date(),
      description: `Health status changed from "${oldStatus}" to "${newStatus}". ${description}`
    });

    this.dinosaurs.set(id, dino);
    console.log(`Updated health status of dinosaur ${dino.name} to: ${newStatus}`);
  }

  // Methods for employees
  addEmployee(employee: ParkEmployee): void {
    this.employees.set(employee.id, employee);
    console.log(`Added employee: ${employee.firstName} ${employee.lastName} (${employee.position})`);
  }

  // Methods for locations
  addEnclosure(enclosure: DinosaurEnclosure): void {
    this.enclosures.set(enclosure.id, enclosure);
    this.locations.set(enclosure.id, enclosure);
    console.log(`Added enclosure: ${enclosure.name}`);
  }

  addLaboratory(lab: ParkLaboratory): void {
    this.laboratories.set(lab.id, lab);
    this.locations.set(lab.id, lab);
    console.log(`Added laboratory: ${lab.name} (${lab.specializations})`);
  }

  // Reporting methods
  generateJurassicParkReport(): string {
    const report = [];
    report.push("=== JURASSIC PARK STATUS REPORT ===");
    report.push(`Report date: ${new Date().toLocaleString()}`);
    report.push(`\nGeneral statistics:`);
    report.push(`- Number of dinosaurs: ${this.dinosaurs.size}`);
    report.push(`- Number of employees: ${this.employees.size}`);
    report.push(`- Number of locations: ${this.locations.size}`);
    report.push(`  - Enclosures: ${this.enclosures.size}`);
    report.push(`  - Laboratories: ${this.laboratories.size}`);

    // Dinosaur statistics
    const healthStatistics = {
      "excellent": 0,
      "good": 0,
      "needs attention": 0,
      "sick": 0,
      "critical": 0
    };

    let predatorsCount = 0;

    for (const dino of this.dinosaurs.values()) {
      healthStatistics[dino.healthStatus]++;
      if (dino.diet === "carnivore") {
        predatorsCount++;
      }
    }

    report.push(`\nDinosaur health statistics:`);
    for (const [status, count] of Object.entries(healthStatistics)) {
      report.push(`- ${status}: ${count}`);
    }

    report.push(`Predators: ${predatorsCount}`);
    report.push(`Herbivores: ${this.dinosaurs.size - predatorsCount}`);

    // Enclosure statistics
    const enclosuresByStatus = {
      "active": 0,
      "inactive": 0,
      "under maintenance": 0,
      "under construction": 0
    };

    for (const enclosure of this.enclosures.values()) {
      enclosuresByStatus[enclosure.status]++;
    }

    report.push(`\nEnclosure statistics:`);
    for (const [status, count] of Object.entries(enclosuresByStatus)) {
      report.push(`- ${status}: ${count}`);
    }

    return report.join("\n");
  }
}

// Example usage
const park = new JurassicParkSystem();

// Adding an enclosure
park.addEnclosure({
  id: "WYB-001",
  name: "T-Rex Paddock",
  dateAdded: new Date(2020, 0, 15),
  lastUpdated: new Date(),
  type: "enclosure",
  coordinates: {
    width: 20.123,
    length: -75.456
  },
  area: 50000, // 5 hectares
  capacity: 2,
  accessLevel: 5,
  securitySystems: ["SEC-001", "SEC-002", "SEC-003"],
  status: "active",
  residents: [],
  environmentType: "forest",
  traits: {
    fenceHeight: 8,
    fenceVoltage: 10000,
    scannersCount: 24,
    cameraCount: 36
  }
});

// Adding a laboratory
park.addLaboratory({
  id: "LAB-001",
  name: "Dr. Wu's Genetics Laboratory",
  dateAdded: new Date(2018, 5, 10),
  lastUpdated: new Date(),
  type: "laboratory",
  coordinates: {
    width: 20.124,
    length: -75.458
  },
  area: 2000,
  capacity: 30,
  accessLevel: 4,
  securitySystems: ["SEC-101", "SEC-102"],
  status: "active",
  specializations: "genetics",
  equipment: ["DNA sequencer", "Sample isolators", "Cryogenic chamber"],
  staff: [],
  researchProjects: [
    {
      id: "PROJ-001",
      name: "Strengthening resistance genes in Triceratops",
      start: new Date(2022, 3, 15),
      status: "in progress"
    }
  ]
});

// Adding a dinosaur
park.addDinosaur({
  id: "DINO-001",
  name: "Rexy",
  dateAdded: new Date(2020, 5, 20),
  lastUpdated: new Date(),
  age: 7,
  gender: "female",
  healthStatus: "good",
  healthHistory: [
    {
      date: new Date(2020, 5, 20),
      description: "Initial examination. All parameters within normal range."
    },
    {
      date: new Date(2021, 2, 15),
      description: "Routine examination. Slightly elevated triglycerides.",
      procedure: "Diet change to one richer in Omega-3 fatty acids"
    }
  ],
  species: "Tyrannosaurus Rex",
  originEra: "Late Cretaceous",
  diet: "carnivore",
  dangerLevel: 5,
  location: "WYB-001",
  traits: {
    height: 4.5,
    length: 12,
    weight: 7200,
    maxSpeed: 32,
    biteForce: 12800
  }
});

// Adding an employee
park.addEmployee({
  id: "EMP-001",
  name: "Employee",
  dateAdded: new Date(2019, 1, 10),
  lastUpdated: new Date(),
  age: 42,
  gender: "male",
  healthStatus: "excellent",
  healthHistory: [
    {
      date: new Date(2022, 1, 5),
      description: "Routine periodic examination. All parameters within normal range."
    }
  ],
  firstName: "Owen",
  lastName: "Grady",
  position: "Raptor Trainer",
  accessLevel: 4,
  departments: ["Behavioral Research", "Animal Care"],
  address: {
    street: "Bungalow 12",
    city: "Isla Nublar",
    postalCode: "00000",
    country: "Costa Rica"
  },
  contact: {
    phone: "+1-555-123-4567",
    email: "owen.grady@jurassicworld.com"
  }
});

// Updating dinosaur health status
park.updateDinosaurHealthStatus(
  "DINO-001",
  "needs attention",
  "Noticed reduced appetite and slight fever."
);

// Generating report
console.log(park.generateJurassicParkReport());

Résumé

L'extension d'interfaces en TypeScript est une technique puissante qui permet de modéliser des hiérarchies de types complexes ainsi que les relations qui les unissent. Dans le contexte de Jurassic Park, elle nous permet de modéliser précisément diverses entités et divers systèmes, des dinosaures et des employés jusqu'aux systèmes avancés de surveillance et de sécurité.

TechniqueUtilisation à Jurassic Park
Extension d'interface de baseHiérarchie des créatures, de la base jusqu'aux espèces spécifiques
Extension de plusieurs interfacesCréation de types hybrides, comme les prédateurs marins
Extension d'interface genericSystèmes de surveillance pour différents types de données
Fusion des déclarations d'interfacesMise à jour des protocoles de sécurité
Compatibilité structurelleTraitement uniforme des différents types de dinosaures par les systèmes de sécurité

Le Dr Wu résume ainsi : « Étendre des interfaces en TypeScript, c'est un peu comme notre travail sur de nouvelles espèces de dinosaures. On part d'une structure de base et on l'enrichit de nouveaux traits et de nouvelles fonctionnalités, créant ainsi des entités toujours plus spécialisées et complexes. Cette flexibilité et cette capacité à réutiliser des définitions existantes nous permettent de créer des systèmes cohérents tout en restant extrêmement variés : c'est essentiel, aussi bien en génétique qu'en programmation. »

Code de cette leçon : index.ts
// Extending interfaces in Jurassic Park
console.log("Extending TypeScript interfaces\n");

// ===========================================
// 1. Extension de base
// ===========================================
console.log("=== EXTENSION DE BASE ===");

// Interface de base
interface Animal {
  name: string;
  age: number;
  weight: number;
}

// Extension de l'interface
interface Dinosaur extends Animal {
  species: string;
  period: "Triassic" | "Jurassic" | "Cretaceous";
  diet: "carnivore" | "herbivore" | "omnivore";
}

const trex: Dinosaur = {
  name: "Rexy",
  age: 5,
  weight: 8000,
  species: "Tyrannosaurus Rex",
  period: "Cretaceous",
  diet: "carnivore"
};

console.log("T-Rex:", trex);

// ===========================================
// 2. Extension multiple
// ===========================================
console.log("\n=== EXTENSION MULTIPLE ===");

interface HasName {
  name: string;
}

interface HasWeight {
  weight: number;
}

interface HasDiet {
  diet: "carnivore" | "herbivore" | "omnivore";
}

// Extending multiple interfaces
interface CompleteDinosaur extends HasName, HasWeight, HasDiet {
  species: string;
  dangerLevel: number;
}

const velociraptor: CompleteDinosaur = {
  name: "Blue",
  weight: 350,
  diet: "carnivore",
  species: "Velociraptor",
  dangerLevel: 8
};

console.log("Velociraptor:", velociraptor);

// ===========================================
// 3. Property overriding
// ===========================================
console.log("\n=== PROPERTY OVERRIDING ===");

interface BasicDinosaur {
  id: string | number;
  name: string;
}

// Narrowing type when extending
interface SpecificDinosaur extends BasicDinosaur {
  id: string; // narrows type de string | number vers string
  trackingCode: string;
}

const trackedDino: SpecificDinosaur = {
  id: "DINO-001", // doit be string
  name: "Rex",
  trackingCode: "TR-XYZ-123"
};

console.log("Tracked dinosaur:", trackedDino);

// ===========================================
// 4. Extension avec des méthodes supplémentaires
// ===========================================
console.log("\n=== EXTENSION AVEC DES MÉTHODES ===");

interface LivingBeing {
  name: string;
  eat(amount: number): void;
  sleep(hours: number): void;
}

interface Predator extends LivingBeing {
  hunt(prey: string): string;
  roar(): string;
  attackPower: number;
}

class TyrannosaurusRex implements Predator {
  name: string;
  attackPower: number;
  energy: number = 100;

  constructor(name: string) {
    this.name = name;
    this.attackPower = 95;
  }

  eat(amount: number): void {
    this.energy += amount * 2;
    if (this.energy > 100) this.energy = 100;
    console.log(`${this.name} ate ${amount}kg. Energy: ${this.energy}`);
  }

  sleep(hours: number): void {
    this.energy += hours * 10;
    if (this.energy > 100) this.energy = 100;
    console.log(`${this.name} slept ${hours}h. Energy: ${this.energy}`);
  }

  hunt(prey: string): string {
    this.energy -= 20;
    return `${this.name} hunts ${prey}! Energy: ${this.energy}`;
  }

  roar(): string {
    this.energy -= 5;
    return `${this.name} roars: ROAAAAAR! (${this.attackPower} power)`;
  }
}

const rexy = new TyrannosaurusRex("Rexy");
console.log(rexy.roar());
console.log(rexy.hunt("Triceratops"));
rexy.eat(50);

// ===========================================
// 5. Chain extending
// ===========================================
console.log("\n=== CHAIN EXTENDING ===");

interface Entity {
  id: string;
}

interface LivingEntity extends Entity {
  isAlive: boolean;
}

interface BreathingEntity extends LivingEntity {
  oxygenLevel: number;
}

interface IntelligentEntity extends BreathingEntity {
  intelligenceLevel: number;
  canCommunicate: boolean;
}

const velociRaptor: IntelligentEntity = {
  id: "VR-001",
  isAlive: true,
  oxygenLevel: 98,
  intelligenceLevel: 85,
  canCommunicate: true
};

console.log("Intelligent entity:", velociRaptor);

// ===========================================
// 6. Generics avec extension
// ===========================================
console.log("\n=== GENERICS AVEC EXTENSION ===");

interface Trackable {
  trackingId: string;
  lastSeen: Date;
}

interface DataEntry extends Trackable {
  data: any;
}

interface DinosaurEntry<T> extends DataEntry {
  dinosaurData: T;
}

interface TRexData {
  species: "Tyrannosaurus Rex";
  teethCount: number;
  biteForce: number;
}

const trexEntry: DinosaurEntry<TRexData> = {
  trackingId: "TRK-001",
  lastSeen: new Date(),
  data: { notes: "Healthy specimen" },
  dinosaurData: {
    species: "Tyrannosaurus Rex",
    teethCount: 60,
    biteForce: 12800
  }
};

console.log("T-Rex entry:", trexEntry);

// ===========================================
// 7. Extension avec Index Signatures
// ===========================================
console.log("\n=== INDEX SIGNATURES ===");

interface BaseConfig {
  version: string;
  enabled: boolean;
}

interface ExtendedConfig extends BaseConfig {
  [key: string]: any; // additional dynamic properties
}

const parkConfig: ExtendedConfig = {
  version: "2.0",
  enabled: true,
  maxCapacity: 10000,
  securityLevel: "high",
  maintenanceMode: false
};

console.log("Park config:", parkConfig);

// ===========================================
// 8. Extension vs Intersection
// ===========================================
console.log("\n=== EXTENDS VS INTERSECTION ===");

// Extends (interfaces)
interface A {
  a: string;
}

interface B extends A {
  b: number;
}

const objB: B = {
  a: "value",
  b: 123
};

// Intersection (types)
type C = {
  c: boolean;
};

type D = C & {
  d: string[];
};

const objD: D = {
  c: true,
  d: ["item1", "item2"]
};

console.log("Interface extension:", objB);
console.log("Type intersection:", objD);

// ===========================================
// 9. Example pratique - Park System
// ===========================================
console.log("\n=== SYSTÈME DU PARK ===");

interface Identifiable {
  id: string;
}

interface Timestamped {
  createdAt: Date;
  updatedAt: Date;
}

interface Locatable {
  latitude: number;
  longitude: number;
}

interface ParkEntity extends Identifiable, Timestamped, Locatable {
  name: string;
  status: "active" | "inactive" | "maintenance";
}

interface Paddock extends ParkEntity {
  capacity: number;
  currentOccupancy: number;
  securityLevel: "low" | "medium" | "high" | "critical";
}

interface DinosaurPark extends ParkEntity {
  paddocks: Paddock[];
  totalDinosaurs: number;
  isOpen: boolean;
}

const jurassicPark: DinosaurPark = {
  id: "PARK-001",
  createdAt: new Date("1993-06-11"),
  updatedAt: new Date(),
  latitude: 22.3964,
  longitude: -159.5261,
  name: "Jurassic Park",
  status: "active",
  paddocks: [],
  totalDinosaurs: 0,
  isOpen: false
};

console.log("Jurassic Park:", jurassicPark);

// ===========================================
// 10. Résumé
// ===========================================
console.log("\n=== RÉSUMÉ ===");
console.log("extends - extending interfaces");
console.log("Extension multiple - inheritance of multiple interfaces");
console.log("Écrasement - type narrowing");
console.log("Méthodes - adding functionality");
console.log("Chaînage - building hierarchy");
console.log("Generics - extension paramétrique");

console.log("\nExtending interfaces mastered!");

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 se passe-t-il quand l’interface B étend l’interface A ?

  2. 2. Une interface en TypeScript peut-elle étendre plusieurs interfaces à la fois ?

Tâches pratiques dans le jeu

  • Éditeur de code

    Crée une interface de base Animal et étends-la en Dinosaur avec les champs supplémentaires era et diet.

  • Tri horizontal

    Ordonne les éléments de l’extension d’interface en TypeScript :

  1. QuestionÉtendre des interfaces
  2. QuestionÉtendre plusieurs interfaces
  3. Exercice de codePratique : Interface avec extends
  4. Remets dans l'ordreSyntaxe de extends pour une interface

Articles utiles