JavaScript and TypeScript course ยท Module 6: TypeScript Basics
Extending interfaces
In this lesson9
Welcome back to Jurassic Park! Today Dr. Henry Wu will guide us through an advanced TypeScript technique that is the foundation of building scalable and flexible systems - extending interfaces. Just as scientists in the park extend the basic traits of dinosaurs with new genetic properties, in TypeScript we can extend basic interfaces with new functionality.
Basic mechanism of extending interfaces
Extending interfaces in TypeScript allows us to create new interfaces on the basis of existing ones, adding new properties or methods. We use the extends keyword:
// 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
};Extending multiple interfaces
An interface can extend multiple other interfaces simultaneously, allowing complex types to be composed from smaller, specialized parts - similar to how scientists combine DNA from different species to create hybrids:
// 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);Extending interfaces vs class inheritance
Extending interfaces is similar to class inheritance, but has several key differences. In Jurassic Park, this can be compared to the difference between "description of an ideal dinosaur" (interface) and "an actual dinosaur" (class):
// 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);Extending and implementing generic interfaces
Generic interfaces are especially powerful when modeling complex systems, such as monitoring different types of data in the park:
// 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;
alertThresholds: 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;
alertThresholds: 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.alertThresholds = {
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.alertThresholds = {
bodyTemperature: 40,
heartRate: 120,
stressLevel: 8
};
} else {
// Default thresholds for other species
this.alertThresholds = {
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.alertThresholds.bodyTemperature &&
this.currentData.bodyTemperature > this.alertThresholds.bodyTemperature) {
console.log(`ALARM: Dinosaur ${this.dinosaurId} body temperature exceeds threshold!`);
thresholdExceeded = true;
}
if (this.alertThresholds.heartRate &&
this.currentData.heartRate > this.alertThresholds.heartRate) {
console.log(`ALARM: Dinosaur ${this.dinosaurId} heart rate exceeds threshold!`);
thresholdExceeded = true;
}
if (this.alertThresholds.stressLevel &&
this.currentData.stressLevel > this.alertThresholds.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.alertThresholds.bodyTemperature!) {
recommendations.push("Lower body temperature");
}
if (this.currentData.stressLevel > this.alertThresholds.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());Interface declaration merging
One of the unique features of TypeScript is the ability to merge multiple declarations of the same interface - similar to how Jurassic Park scientists can update their handling protocols as they gain new information:
// 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 {
responsiblePersonnel: 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",
responsiblePersonnel: ["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.responsiblePersonnel.forEach(person => console.log(`- ${person}`));
console.log(`\nCommunication channels: ${protocol.communicationChannels.join(", ")}`);
console.log(`\nAlarm message: "${protocol.alarmMessage}"`);
}
displayProtocol(protocolAlpha);Structural compatibility of interfaces
TypeScript uses structural compatibility, meaning types are compatible if they have the same structure, regardless of their names. It's like in Jurassic Park - if a dinosaur behaves like a T-Rex and looks like a T-Rex, from the security system's perspective it should be treated like a 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 abstract types
Comparing interfaces with abstract types (abstract classes) in the context of 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()}`);Key differences:
| Feature | Interface | Abstract class |
|---|---|---|
| Implementation | Definition only, no implementation | Can contain method implementations |
| Inheritance | Class can implement multiple interfaces | Class can only inherit from one abstract class |
| Constructor | No constructor | Can have a constructor |
| Runtime code | Interfaces generate no JavaScript code | Abstract classes generate JavaScript code |
| Access modifiers | Cannot use modifiers (private, protected) | Can use access modifiers |
| Use | Defining a contract | Defining base functionality with partial implementation |
Practical application of interface extension
Let's now see a comprehensive example illustrating how interface extension can be used in the Jurassic Park management system:
// Base interface for all entities in the park
interface JurassicParkBase {
id: string;
name: string;
dateAdded: Date;
lastUpdate: 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 {
specialization: "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.lastUpdate = 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.specialization})`);
}
// 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 healthStats = {
"excellent": 0,
"good": 0,
"needs attention": 0,
"sick": 0,
"critical": 0
};
let predatorsCount = 0;
for (const dino of this.dinosaurs.values()) {
healthStats[dino.healthStatus]++;
if (dino.diet === "carnivore") {
predatorsCount++;
}
}
report.push(`\nDinosaur health statistics:`);
for (const [status, count] of Object.entries(healthStats)) {
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: "ENC-001",
name: "T-Rex Paddock",
dateAdded: new Date(2020, 0, 15),
lastUpdate: 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),
lastUpdate: new Date(),
type: "laboratory",
coordinates: {
width: 20.124,
length: -75.458
},
area: 2000,
capacity: 30,
accessLevel: 4,
securitySystems: ["SEC-101", "SEC-102"],
status: "active",
specialization: "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),
lastUpdate: 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: "ENC-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),
lastUpdate: 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());Summary
Extending interfaces in TypeScript is a powerful technique that allows modeling complex type hierarchies and relationships between them. In the context of Jurassic Park, it enables us to precisely model various entities and systems, from dinosaurs and employees to advanced monitoring and security systems.
| Technique | Use in Jurassic Park |
|---|---|
| Basic interface extension | Hierarchy of creatures from base to specific species |
| Extending multiple interfaces | Creating hybrid types, like marine predators |
| Generic interface extension | Monitoring systems for different types of data |
| Interface declaration merging | Updating security protocols |
| Structural compatibility | Uniform treatment of different dinosaur types by security systems |
Dr. Wu summarizes: "Extending interfaces in TypeScript resembles our work on new dinosaur species. We start from a basic structure and extend it with new traits and functionality, creating increasingly specialized and complex entities. This flexibility and ability to reuse existing definitions means we can create cohesive, yet highly diverse systems - key in both genetics and programming."
Code for this lesson: index.ts
// Extending interfaces in Jurassic Park
console.log("Extending TypeScript interfaces\n");
// ===========================================
// 1. Basic extension
// ===========================================
console.log("=== BASIC EXTENSION ===");
// Base interface
interface Animal {
name: string;
age: number;
weight: number;
}
// Extending the 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. Multiple extension
// ===========================================
console.log("\n=== MULTIPLE EXTENSION ===");
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 the type from string | number to string
trackingCode: string;
}
const trackedDino: SpecificDinosaur = {
id: "DINO-001", // must be a string
name: "Rex",
trackingCode: "TR-XYZ-123"
};
console.log("Tracked dinosaur:", trackedDino);
// ===========================================
// 4. Extending with additional methods
// ===========================================
console.log("\n=== EXTENDING WITH METHODS ===");
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 with extension
// ===========================================
console.log("\n=== GENERICS WITH 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. Extending with 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. Practical example - Park System
// ===========================================
console.log("\n=== PARK SYSTEM ===");
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. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("extends - extending interfaces");
console.log("Multiple extension - inheriting from several interfaces");
console.log("Overriding - type narrowing");
console.log("Methods - adding functionality");
console.log("Chains - building a hierarchy");
console.log("Generics - parametric extension");
console.log("\nExtending interfaces mastered!");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. What happens when interface B extends interface A?
2. Can an interface in TypeScript extend multiple interfaces at the same time?
Hands-on tasks in the game
- Code editor
Create a base interface Animal and extend it to Dinosaur with additional fields era and diet.
- Horizontal ordering
Arrange the elements of interface extension in TypeScript: