JavaScript and TypeScript course ยท Module 6: TypeScript Basics
Final project: Typed Jurassic Park management system
In this lesson4
Congratulations - you've reached the final project of the TypeScript fundamentals module! Over the past lessons you've learned powerful typing tools: from basic types, through arrays, tuples and enums, all the way to interfaces, union types and aliases. Now the time has come to combine this knowledge into one comprehensive project.
Imagine that the Jurassic Park programming team has finally decided to rewrite their systems from plain JavaScript to TypeScript. After too many incidents caused by type errors - from incorrectly passed power parameters, through mixed up dinosaur species, to security system failures due to undefined - management made a decision: "Never again!". Your task is to create the foundation of a new, fully typed park management system.
In this project you will build a complete type and interface system for Jurassic Park, which will ensure type safety at every level of the application.
Project goal
You will create a typed Jurassic Park management system consisting of four areas:
- Dinosaur type system - enums, interfaces and unions describing all aspects of dinosaurs
- Sector management system - interfaces and types for park infrastructure
- Security system - types for events, alerts and protocols
- Central management system - combining all types into a cohesive system
Functional requirements
1. Dinosaur type system (Enums, interfaces, aliases)
The first area is a precise data model describing the dinosaurs in the park. We use enums for constant values, interfaces for object structure, and type aliases for complex combinations.
// Enums - constant values in the system
enum Diet {
Carnivore = "carnivore",
Herbivore = "herbivore",
Omnivore = "omnivore",
Piscivore = "piscivore"
}
enum Era {
Triassic = "triassic",
Jurassic = "jurassic",
Cretaceous = "cretaceous"
}
enum ThreatLevel {
Minimal = 1,
Low = 2,
Moderate = 3,
High = 4,
Extreme = 5
}
enum DinoStatus {
Healthy = "healthy",
Sick = "sick",
Sleeping = "sleeping",
Feeding = "feeding",
Agitated = "agitated",
Escaped = "escaped"
}
// Type alias - dinosaur species
type Species =
| "Tyrannosaurus Rex"
| "Velociraptor"
| "Triceratops"
| "Brachiosaurus"
| "Stegosaurus"
| "Pteranodon"
| "Dilophosaurus"
| "Gallimimus"
| "Parasaurolophus"
| "Ankylosaurus";
// Interface - dinosaur health data
interface DinoHealth {
weight: number; // in kilograms
height: number; // in meters
heartRate: number; // beats per minute
temperature: number; // degrees Celsius
lastFed: Date;
lastCheckup: Date;
conditions: string[]; // list of health conditions
}
// Interface - full dinosaur profile
interface Dinosaur {
id: string;
name: string;
species: Species; // Type alias
diet: Diet; // Enum
era: Era; // Enum
threatLevel: ThreatLevel; // Enum
status: DinoStatus; // Enum
health: DinoHealth; // Nested interface
sectorId: string;
trackingChipActive: boolean;
dateAdded: Date;
}
// Union type - dinosaur search filter
type DinoSearchCriteria =
| { by: "species"; value: Species }
| { by: "diet"; value: Diet }
| { by: "threatLevel"; minLevel: ThreatLevel }
| { by: "status"; value: DinoStatus }
| { by: "sector"; sectorId: string };
// Function with types
function searchDinosaurs(
dinosaurs: Dinosaur[],
criteria: DinoSearchCriteria
): Dinosaur[] {
switch (criteria.by) {
case "species":
return dinosaurs.filter(d => d.species === criteria.value);
case "diet":
return dinosaurs.filter(d => d.diet === criteria.value);
case "threatLevel":
return dinosaurs.filter(d => d.threatLevel >= criteria.minLevel);
case "status":
return dinosaurs.filter(d => d.status === criteria.value);
case "sector":
return dinosaurs.filter(d => d.sectorId === criteria.sectorId);
}
}Notice how TypeScript enforces completeness of handling in switch - if you add a new variant to DinoSearchCriteria, the compiler will remind you to handle the new case.
2. Sector management system (Interfaces and complex types)
The second area is the park infrastructure model - sectors, fences, power systems and monitoring.
// Union type - fence type
type FenceType = "electric" | "concrete" | "reinforced" | "moat";
// Fence interface
interface Fence {
id: string;
type: FenceType;
voltage: number; // 0 for non-electric
integrity: number; // 0-100%
lastMaintenance: Date;
requiresRepair: boolean;
}
// Enum - sector status
enum SectorStatus {
Operational = "operational",
Maintenance = "maintenance",
Lockdown = "lockdown",
Evacuated = "evacuated",
Offline = "offline"
}
// Interface - power system
interface PowerSystem {
mainPowerLevel: number; // 0-100%
backupPowerLevel: number; // 0-100%
isBackupActive: boolean;
solarPanelsOnline: number; // number of active panels
generatorStatus: "running" | "standby" | "failed";
}
// Sector interface with nested types
interface Sector {
id: string;
name: string;
status: SectorStatus;
dinosaurs: Dinosaur[];
fences: Fence[];
power: PowerSystem;
capacity: number; // maximum number of dinosaurs
securityLevel: ThreatLevel;
staff: StaffMember[];
}
// Type alias - staff role
type StaffRole =
| "veterinarian"
| "guard"
| "technician"
| "scientist"
| "manager"
| "guide";
// Staff member interface
interface StaffMember {
id: string;
name: string;
role: StaffRole;
assignedSector: string;
clearanceLevel: ThreatLevel; // Reusing enum in a different context
onDuty: boolean;
specializations: string[];
}
// Type - sector status summary
type SectorSummary = {
sectorId: string;
sectorName: string;
status: SectorStatus;
dinoCount: number;
avgFenceIntegrity: number;
powerStatus: "stable" | "low" | "critical";
staffOnDuty: number;
alerts: number;
};
// Function generating the summary
function getSectorSummary(sector: Sector): SectorSummary {
const avgFence = sector.fences.reduce(
(sum, f) => sum + f.integrity, 0
) / sector.fences.length;
const powerStatus: SectorSummary["powerStatus"] =
sector.power.mainPowerLevel > 60 ? "stable" :
sector.power.mainPowerLevel > 30 ? "low" : "critical";
return {
sectorId: sector.id,
sectorName: sector.name,
status: sector.status,
dinoCount: sector.dinosaurs.length,
avgFenceIntegrity: Math.round(avgFence),
powerStatus,
staffOnDuty: sector.staff.filter(s => s.onDuty).length,
alerts: 0
};
}Interfaces build hierarchically - Sector contains arrays of Dinosaur[], Fence[] and StaffMember[], creating a rich data model.
3. Security system (Union types and aliases)
The third area is the security event and alert system, which makes heavy use of union types to precisely model different types of incidents.
// Union types for security events - each event has a different structure
type SecurityEvent =
| {
type: "fence_breach";
sectorId: string;
fenceId: string;
dinosaurId: string;
severity: "warning" | "critical";
}
| {
type: "power_outage";
sectorId: string;
affectedSystems: string[];
backupActivated: boolean;
}
| {
type: "dinosaur_escape";
dinosaurId: string;
species: Species;
lastKnownSector: string;
threatLevel: ThreatLevel;
}
| {
type: "sensor_failure";
sectorId: string;
sensorIds: string[];
possibleCause: "damage" | "power" | "sabotage" | "unknown";
}
| {
type: "unauthorized_access";
location: string;
personId: string | null;
timestamp: Date;
};
// Enum - alert priority
enum AlertPriority {
Info = "INFO",
Warning = "WARNING",
Danger = "DANGER",
Critical = "CRITICAL",
Evacuation = "EVACUATION"
}
// Alert interface
interface SecurityAlert {
id: string;
event: SecurityEvent;
priority: AlertPriority;
createdAt: Date;
acknowledgedBy: string | null; // Staff member ID or null
resolved: boolean;
notes: string[];
}
// Type - threat response protocol
type ResponseProtocol = {
alertId: string;
actions: ProtocolAction[];
estimatedTime: number; // in minutes
requiredClearance: ThreatLevel;
};
// Union type - protocol action
type ProtocolAction =
| { action: "lockdown"; sectors: string[] }
| { action: "evacuate"; sectors: string[]; priority: "staff" | "visitors" | "all" }
| { action: "deploy_team"; teamType: StaffRole; targetSector: string }
| { action: "activate_backup"; systems: string[] }
| { action: "track_dinosaur"; dinosaurId: string; useHelicopter: boolean };
// Event handling function with type narrowing
function handleSecurityEvent(event: SecurityEvent): ResponseProtocol {
const actions: ProtocolAction[] = [];
let estimatedTime = 10;
let requiredClearance = ThreatLevel.Moderate;
switch (event.type) {
case "fence_breach":
actions.push({ action: "lockdown", sectors: [event.sectorId] });
actions.push({ action: "deploy_team", teamType: "technician", targetSector: event.sectorId });
if (event.severity === "critical") {
actions.push({ action: "evacuate", sectors: [event.sectorId], priority: "visitors" });
requiredClearance = ThreatLevel.High;
}
break;
case "dinosaur_escape":
actions.push({ action: "track_dinosaur", dinosaurId: event.dinosaurId, useHelicopter: event.threatLevel >= ThreatLevel.High });
actions.push({ action: "lockdown", sectors: [event.lastKnownSector] });
actions.push({ action: "deploy_team", teamType: "guard", targetSector: event.lastKnownSector });
estimatedTime = 60;
requiredClearance = ThreatLevel.Extreme;
break;
case "power_outage":
actions.push({ action: "activate_backup", systems: event.affectedSystems });
actions.push({ action: "deploy_team", teamType: "technician", targetSector: event.sectorId });
if (!event.backupActivated) {
actions.push({ action: "lockdown", sectors: [event.sectorId] });
requiredClearance = ThreatLevel.High;
}
break;
case "sensor_failure":
actions.push({ action: "deploy_team", teamType: "technician", targetSector: event.sectorId });
if (event.possibleCause === "sabotage") {
actions.push({ action: "lockdown", sectors: [event.sectorId] });
requiredClearance = ThreatLevel.Extreme;
}
break;
case "unauthorized_access":
actions.push({ action: "deploy_team", teamType: "guard", targetSector: event.location });
break;
}
return {
alertId: `PROTOCOL-${Date.now()}`,
actions,
estimatedTime,
requiredClearance
};
}Type narrowing in switch allows TypeScript to automatically narrow the event type - in the case "fence_breach" block TypeScript knows that event has fenceId and severity fields.
4. Central management system (Combining types)
The last area is the central system that combines all the above types into a cohesive park management interface.
// Interface for the entire park
interface JurassicPark {
name: string;
sectors: Sector[];
totalDinosaurs: number;
activeAlerts: SecurityAlert[];
operationalStatus: "open" | "restricted" | "closed" | "emergency";
}
// Type - daily report
type DailyReport = {
date: string;
parkStatus: JurassicPark["operationalStatus"]; // Reusing type from interface
sectorSummaries: SectorSummary[];
incidentCount: number;
resolvedIncidents: number;
dinosaurStats: {
total: number;
byDiet: Record<Diet, number>; // Record with enum as key
byStatus: Record<DinoStatus, number>;
escaped: number;
};
staffStats: {
totalOnDuty: number;
byRole: Record<StaffRole, number>; // Record with type alias as key
};
recommendations: string[];
};
// Function generating the report
function generateDailyReport(park: JurassicPark): DailyReport {
// Initialize counters with enums
const byDiet: Record<Diet, number> = {
[Diet.Carnivore]: 0,
[Diet.Herbivore]: 0,
[Diet.Omnivore]: 0,
[Diet.Piscivore]: 0
};
const byStatus: Record<DinoStatus, number> = {
[DinoStatus.Healthy]: 0,
[DinoStatus.Sick]: 0,
[DinoStatus.Sleeping]: 0,
[DinoStatus.Feeding]: 0,
[DinoStatus.Agitated]: 0,
[DinoStatus.Escaped]: 0
};
// Counting dinosaurs
const allDinos = park.sectors.flatMap(s => s.dinosaurs);
allDinos.forEach(dino => {
byDiet[dino.diet]++;
byStatus[dino.status]++;
});
// Sector summaries
const sectorSummaries = park.sectors.map(getSectorSummary);
// Recommendations based on data
const recommendations: string[] = [];
if (byStatus[DinoStatus.Escaped] > 0) {
recommendations.push(`CRITICAL: ${byStatus[DinoStatus.Escaped]} dinosaur(s) escaped!`);
}
if (byStatus[DinoStatus.Agitated] > allDinos.length * 0.3) {
recommendations.push("WARNING: Over 30% of dinosaurs are agitated - investigate the cause");
}
const lowPowerSectors = sectorSummaries.filter(s => s.powerStatus === "critical");
if (lowPowerSectors.length > 0) {
recommendations.push(
`Critical power level in sectors: ${lowPowerSectors.map(s => s.sectorName).join(", ")}`
);
}
return {
date: new Date().toISOString().split("T")[0],
parkStatus: park.operationalStatus,
sectorSummaries,
incidentCount: park.activeAlerts.length,
resolvedIncidents: park.activeAlerts.filter(a => a.resolved).length,
dinosaurStats: {
total: allDinos.length,
byDiet,
byStatus,
escaped: byStatus[DinoStatus.Escaped]
},
staffStats: {
totalOnDuty: park.sectors.flatMap(s => s.staff).filter(s => s.onDuty).length,
byRole: {
veterinarian: 0, guard: 0, technician: 0,
scientist: 0, manager: 0, guide: 0
}
},
recommendations
};
}Implementation tips
When designing the type system, remember the key principles:
Use enums for constant sets of values:
// Good - values are constant and known in advance
enum Diet { Carnivore = "carnivore", Herbivore = "herbivore" }
// Bad - too dynamic data for an enum
enum DinosaurName { Rex = "Rex", Blue = "Blue" } // Names can be arbitraryInterfaces for object structures, aliases for unions and combinations:
// Interface - describes the shape of an object
interface Dinosaur {
name: string;
species: Species;
}
// Alias - combines types, creates variants
type SearchResult = Dinosaur | null;
type DinoFilter = (dino: Dinosaur) => boolean;
type DinoOrError = { success: true; data: Dinosaur } | { success: false; error: string };Discriminated union types for events:
// The "type" field allows TypeScript to distinguish variants
type Event =
| { type: "A"; fieldA: string }
| { type: "B"; fieldB: number };
function handle(event: Event) {
if (event.type === "A") {
// TypeScript knows fieldA is here
console.log(event.fieldA);
}
}Record for creating mappings from enums:
// Automatic enum โ value map
const dietLabels: Record<Diet, string> = {
[Diet.Carnivore]: "Carnivore - feed with meat",
[Diet.Herbivore]: "Herbivore - feed with plants",
[Diet.Omnivore]: "Omnivore - mixed diet",
[Diet.Piscivore]: "Piscivore - feed with fish"
};Good luck!
This project is your chance to prove that you understand the power of the TypeScript type system. In a real Jurassic Park every mistake can cost lives - and TypeScript is your fence protecting against type errors. As Dr. Alan Grant said: "Dinosaurs and man - two species separated by 65 million years of evolution - suddenly must live side by side again." And TypeScript makes that coexistence safe and predictable.
Create your typed management system in the editor below. Define at least three enums, four interfaces, two union types and one function using these types.
Code for this lesson: index.ts
// Final project: A typed Jurassic Park management system
// Combine: TypeScript types, interfaces, enums, unions, aliases
// === 1. ENUMS AND CONSTANTS ===
// TODO: Define enums for the park system
enum Diet {
Carnivore = "carnivore",
Herbivore = "herbivore",
Omnivore = "omnivore",
}
enum ThreatLevel {
Minimal = 1,
Low = 2,
Moderate = 3,
High = 4,
Extreme = 5,
}
// TODO: Add the enums DinoStatus and Era
// === 2. INTERFACES ===
// TODO: Create the interface IDinosaur
interface IDinosaur {
id: string;
name: string;
species: string;
diet: Diet;
weight: number;
threatLevel: ThreatLevel;
// TODO: Add the remaining fields: isHealthy, enclosure, era
}
// TODO: Create the interface IEnclosure
interface IEnclosure {
id: string;
name: string;
// TODO: Add the fields: capacity, currentOccupants, securityLevel, isElectrified
}
// === 3. UNION TYPES AND ALIASES ===
// TODO: Create the type AlertType = "breach" | "health" | "power" | "weather"
// TODO: Create the type SecurityEvent as a discriminated union
// === 4. TYPED FUNCTIONS ===
// TODO: Create a typed function registerDinosaur
function registerDinosaur(data: Omit<IDinosaur, "id">): IDinosaur {
// TODO: Add an automatic ID and return the full object
return { id: "DINO-001", ...data };
}
// TODO: Create a function assignToEnclosure(dino: IDinosaur, enclosure: IEnclosure): boolean
// TODO: Create a function generateSecurityReport(dinosaurs: IDinosaur[]): string
// === 5. SYSTEM TEST ===
// TODO: Create a few dinosaurs and assign them to enclosures
// TODO: Generate a security report
console.log("Typed management system started!");Docs entries used in this lesson
Spotted a mistake in this lesson?