JavaScript and TypeScript course ยท Module 7: Advanced TypeScript

Implementing Interfaces

24 min read ยท
In this lesson10

"In Jurassic Park, everything must operate according to strict protocols," explains Claire Dearing, the operations director. "Every employee has a clearly defined scope of duties, and every system must meet specific requirements. We don't care how exactly a guard watches the raptor enclosure - what matters is that they do their job according to security procedures."

In the TypeScript world, interfaces play a similar role - they define a "contract" that classes must fulfill, without specifying how exactly they should do it. In this exercise, you will learn how to design and implement interfaces by creating an advanced management system for Jurassic Park.

Interface Basics

An interface in TypeScript is a structure that defines the shape of an object - what properties and methods it should have, without specifying their implementation. You can think of an interface as a contract or protocol that a class must follow.

Let's look at the basic interface syntax:

// Interface definition
interface ParkStaffMember {
  // 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 ParkStaffMember {
  // Implementation of all required properties
  id: string;
  firstName: string;
  lastName: string;
  accessLevel: number;
  private isActive: boolean = false;

  constructor(id: string, firstName: string, lastName: string) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.accessLevel = 2; // Standard level for guards
  }

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

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

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

  // Additional methods specific to the guard
  patrolSector(sectorId: string): void {
    if (!this.isActive) {
      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 ParkStaffMember {
  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("Velociraptor DNA");

In the example above:

  1. We defined the ParkStaffMember interface specifying what properties and methods every employee must have
  2. We created two different classes implementing this interface - each in its own way
  3. Both classes must provide all required properties and methods, but can implement them differently
  4. Classes can also add their own additional methods and properties

Optional and Read-Only Properties

TypeScript interfaces allow for more advanced property definitions:

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 isActive: boolean = false;

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

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

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

  checkStatus(): string {
    return `Fence system ${this.id}: ${this.isActive ? "ACTIVE" : "INACTIVE"}, Voltage: ${this.voltage}V`;
  }

  // Custom method, not required by the interface
  increaseVoltage(increment: number): void {
    if (!this.isActive) {
      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,
  autoRestarts: 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";

In this example:

  1. We defined a readonly property that cannot be modified after initialization
  2. We added an optional property advancedOptions (marked with ?)
  3. The implementation checks whether the optional property exists before using it

Extending Interfaces

Interfaces, like classes, can extend other interfaces, inheriting their properties and methods:

// 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;
  era: "triassic" | "jurassic" | "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;
  era: "triassic" | "jurassic" | "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();

In this example we created a hierarchy of interfaces:

  1. Animal - the base interface for all animals
  2. Dinosaur - extends Animal with properties specific to dinosaurs
  3. PredatoryDinosaur - extends Dinosaur with properties specific to predators

The TyrannosaurusRex class implements the most specialized interface PredatoryDinosaur, which means it must provide all properties and methods from all three interfaces.

Interfaces vs Types

TypeScript also offers type aliases (type), which have similar capabilities to interfaces, but there are some differences between them:

// 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;
  }
}

Main differences between interfaces and types:

  1. Extensibility:

    • Interfaces can be extended later (declaration merging)
    • Types are closed after definition
    // Interface can be extended with additional declarations
    interface DinosaurDiagnosis {
      examinationResult: string;
    }
    
    // Adding new properties to an existing interface
    interface DinosaurDiagnosis {
      performedDate: 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. Combining:

    • Interfaces use extends
    • Types use the intersection operator &
  3. Advanced constructs:

    • Types can represent unions, intersections, and other complex types
    • Interfaces are limited to describing the shape of objects
// Advanced types that cannot be expressed with interfaces
type DinosaurStatus = "healthy" | "sick" | "under 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 PartialDinosaur = Optional<Dinosaur>;

Interfaces for Functions and Methods

Interfaces can also define the shape of functions and class constructors:

// 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());

Index Signatures in Interfaces

Interfaces can also define indexed types that allow dynamic access to properties:

// 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()}`);

Implementing Multiple Interfaces

A class can implement multiple interfaces simultaneously:

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

// Interface for alarm systems
interface AlarmSystem {
  triggerAlarm(): 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 monitoringActive: 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.monitoringActive = true;
    console.log(`System ${this.id}: Monitoring started.`);
  }

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

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

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

  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.triggerAlarm();
    // Access is already blocked by triggerAlarm()
  }
}

// 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 unlocking

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

Implementing Interfaces with Name Conflicts

What happens when we implement two interfaces with properties of the same name?

// 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 ConflictingSystem 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

How to solve the problem of incompatible interfaces:

// 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;
  }
}

Practical Example: Jurassic Park Management System

Below is a comprehensive example using interfaces to create a management system for Jurassic Park:

// Interface for a basic manageable entity
interface InventoryItem {
  readonly id: string;
  name: string;
  category: string;
  dateAdded: 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<{ date: Date, description: string, performedBy: string }>;

  scheduleMaintenance(date: Date): void;
  performMaintenance(description: string, performedBy: 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";
  dateAdded: 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<{ date: Date, description: string, performedBy: 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.dateAdded = 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,
      dateAdded: this.dateAdded,
      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(date: Date): void {
    this.plannedMaintenance = date;
    console.log(`Device ${this.id}: Scheduled maintenance for ${date.toLocaleDateString()}`);
  }

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

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

    // 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 ${performedBy}: ${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 = "Electric Fence";
  dateAdded: 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<{ date: Date, description: string, performedBy: 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.dateAdded = 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(date: Date): void {
    this.plannedMaintenance = date;
    console.log(`Fence ${this.id}: Scheduled maintenance for ${date.toLocaleDateString()}`);
  }

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

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

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

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

    // Resetting planned maintenance
    this.plannedMaintenance = null;

    console.log(`Fence ${this.id}: Maintenance performed by ${performedBy}: ${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(`Fence ${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--- Initializing fence ---");
  const fence = new ElectricFence(
    "FENCE-002",
    "T-Rex enclosure fence",
    "T-REX-A",
    1200, // 1200 meters long
    15000, // 15000V
    true // with 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--- Incident simulation ---");
  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("Fence status:", fence.getInfo());

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

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

// Running the demonstration
demonstrateParkSystem();

Summary

In this exercise, we learned about TypeScript interfaces - a powerful tool for defining contracts and creating consistent structures in code.

Key features of interfaces:

  1. Define the shape of objects - specify what properties and methods objects of a given type must have
  2. Support for polymorphism - different classes can implement the same interface in different ways
  3. Loose coupling - focus on what objects do, not how they are implemented
  4. Flexibility - optional properties, read-only, index signatures, etc.
  5. Extensibility - interfaces can inherit from other interfaces

As Claire Dearing would summarize: "In Jurassic Park, just like in good software architecture, everyone has their role and responsibilities. Interfaces allow us to clearly define these roles, ensuring that all systems work well together - without surprises. And believe me, surprises in a park full of dinosaurs are the last thing we need."

Code for this lesson: index.ts
// Implementing interfaces - Jurassic Park
console.log("=== IMPLEMENTING INTERFACES ===\n");

// ===========================================
// 1. Defining the 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. A class that implements many 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} moved to ${this.getLocation()}`);
  }

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

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

  // IContainable
  checkContainment(): string {
    return this.isContained
      ? `${this.name} is safely inside enclosure ${this.enclosureId}`
      : `ALARM! ${this.name} got out of enclosure ${this.enclosureId}!`;
  }
}

// ===========================================
// 3. Functions that work with interfaces
// ===========================================

function trackEntity(entity: ITrackable): void {
  console.log(`Tracking: ${entity.trackingId} at position ${entity.getLocation()}`);
}

function feedEntity(entity: IFeedable): void {
  console.log(`Diet: ${entity.diet}`);
  console.log(`Hungry: ${entity.isHungry() ? "YES" : "NO"}`);
}

function checkSafety(entities: IContainable[]): void {
  console.log("\n--- Security report ---");
  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("--- Tracking ---");
trackEntity(velociraptor);
velociraptor.updateLocation(45, 120);
trackEntity(velociraptor);

console.log("\n--- Feeding ---");
console.log(velociraptor.feed("Goat"));
console.log(brachio.feed("Palm leaves"));
feedEntity(brachio);

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

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

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the implements keyword do in TypeScript?

  2. 2. How do you define a generic interface in TypeScript?

Hands-on tasks in the game

  • Code editor

    Implement the ITrackable and IFeedable interfaces for park entities

  • Horizontal ordering

    Arrange the elements of a generic interface:

  1. QuestionInterface Implementation
  2. Coding taskImplementing Interfaces
  3. Put in orderGeneric Interface Syntax
  4. QuestionGeneric Interface

Useful articles