JavaScript and TypeScript course ยท Module 6: TypeScript Basics
Complex types (array, tuple, enum)
In this lesson7
Welcome back to Jurassic Park! After getting to know the basic data types in TypeScript, we're ready to move on to more advanced structures. In today's lesson Dr. Wu will take us to the laboratory, where we'll experiment with more complex data types.
Just as in Jurassic Park it's not enough to know individual species - you need to understand how entire ecosystems and dinosaur hierarchies work - so in TypeScript it's not enough to know only the basic types. We need to learn how to organize data into more complex structures.
Array types (Array)
Arrays in TypeScript are like enclosures in Jurassic Park - they serve to store collections of similar elements. We can define the type of an array in two ways:
// Defining an array of dinosaurs
let dinosaurs: string[] = ["Tyrannosaurus", "Velociraptor", "Triceratops"];
// Alternative notation
let dinosaursAlt: Array<string> = ["Brachiosaurus", "Stegosaurus", "Ankylosaurus"];
// Array of numbers - e.g. dinosaur weights in kilograms
let weights: number[] = [7500, 350, 8500, 35000, 5500];
// Accessing array elements
console.log(`First dinosaur: ${dinosaurs[0]}`); // Tyrannosaurus
console.log(`Number of dinosaurs: ${dinosaurs.length}`); // 3
// Adding to the array
dinosaurs.push("Spinosaurus");
console.log(`Now we have ${dinosaurs.length} dinosaurs`); // 4
// Iterating over the array
dinosaurs.forEach(dino => {
console.log(`Studying behavior: ${dino}`);
});Arrays can also store more complex objects:
// Defining an interface for a dinosaur object
interface Dinosaur {
id: number;
name: string;
species: string;
isPredator: boolean;
ageMillionYears: number;
}
// Array of dinosaur objects
const specimenCollection: Dinosaur[] = [
{ id: 1, name: "Rex", species: "Tyrannosaurus", isPredator: true, ageMillionYears: 68 },
{ id: 2, name: "Blue", species: "Velociraptor", isPredator: true, ageMillionYears: 75 },
{ id: 3, name: "Trixie", species: "Triceratops", isPredator: false, ageMillionYears: 68 }
];
// Filtering the array - find all predators
const predators = specimenCollection.filter(dino => dino.isPredator);
console.log(`Number of predators: ${predators.length}`); // 2
// Transforming the array - get only dinosaur names
const dinosaurNames = specimenCollection.map(dino => dino.name);
console.log(`Specimen names: ${dinosaurNames.join(", ")}`); // "Rex, Blue, Trixie"Multidimensional arrays
Multidimensional arrays can be used to represent more complex data, such as a map of enclosures in Jurassic Park:
// Two-dimensional array representing the Jurassic Park map
// 0 = inaccessible terrain, 1 = path, 2 = herbivore enclosure, 3 = predator enclosure
const jurassicParkMap: number[][] = [
[0, 0, 2, 2, 2, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 3, 3, 3, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 2, 2, 2, 0, 0]
];
// Checking what is at a given position
function checkTerrain(x: number, y: number): string {
const terrain = jurassicParkMap[y][x];
switch (terrain) {
case 0: return "Inaccessible terrain";
case 1: return "Visitor path";
case 2: return "Herbivore enclosure";
case 3: return "WARNING! Predator enclosure!";
default: return "Unknown terrain";
}
}
console.log(checkTerrain(2, 2)); // "WARNING! Predator enclosure!"Arrays with different element types - Tuple
Tuples are a special kind of array where we know the exact number of elements and their types. It's like transporting dinosaurs - the type of vehicle and the special safety measures appropriate for each species must be strictly defined.
// Tuple representing employee data: [id, name, position, access level]
type ParkEmployee = [number, string, string, number];
const employees: ParkEmployee[] = [
[1, "John Hammond", "Director", 5],
[2, "Dr. Alan Grant", "Paleontologist", 4],
[3, "Dr. Ellie Sattler", "Paleobotanist", 4],
[4, "Dennis Nedry", "Programmer", 3]
];
// Tuple with different element types
// Format: [DNA code, species, age in millions of years, is predator]
type GeneticCode = [string, string, number, boolean];
const tRexCode: GeneticCode = ["ACGTTCAGC", "Tyrannosaurus Rex", 68, true];
// Tuple destructuring
const [dnaCode, species, age, predator] = tRexCode;
console.log(`DNA: ${dnaCode}, Species: ${species}`);
// Optional tuple elements (from TypeScript 3.0)
// Format: [id, name, optional RFID tag]
type MuseumSpecimen = [number, string, string?];
const dinosaurSpecimen: MuseumSpecimen = [42, "Velociraptor Skull"];
const taggedSpecimen: MuseumSpecimen = [43, "Dinosaur Egg", "RFID-J-43"];Enumeration types (Enum)
Enumeration types (Enum) in TypeScript are like safety categories in Jurassic Park - they help define a set of named constants that can be used in code.
// Defining an enumeration type for threat categories
enum ThreatCategory {
Low, // 0
Moderate, // 1
High, // 2
Critical, // 3
RedLevel // 4
}
// Using the enum
let tRexEnclosureThreat: ThreatCategory = ThreatCategory.High;
if (tRexEnclosureThreat >= ThreatCategory.High) {
console.log("Double electric fencing recommended!");
}
// Accessing by value
const categoryDescription = (level: ThreatCategory): string => {
switch (level) {
case ThreatCategory.Low: return "Standard precautions";
case ThreatCategory.Moderate: return "Increased vigilance";
case ThreatCategory.High: return "Double security";
case ThreatCategory.Critical: return "No visitor access";
case ThreatCategory.RedLevel: return "Park evacuation!";
default: return "Unknown threat level";
}
};
console.log(categoryDescription(tRexEnclosureThreat)); // "Double security"
// Enum with specified values
enum DinosaurStatus {
Inactive = 0,
LimitedActivity = 5,
Active = 10,
VeryActive = 15,
InterventionRequired = 20
}
let statusRexT: DinosaurStatus = DinosaurStatus.VeryActive;
console.log(`T-Rex activity level: ${statusRexT}`); // 15
// String enum
enum DinosaurSpecies {
TRex = "Tyrannosaurus Rex",
Raptor = "Velociraptor",
Tric = "Triceratops",
Stego = "Stegosaurus",
Brach = "Brachiosaurus"
}
let publicFavorite: DinosaurSpecies = DinosaurSpecies.TRex;
console.log(`Today's attraction: ${publicFavorite}`); // "Tyrannosaurus Rex"Const Enum
Const Enum is a TypeScript optimization that eliminates the enum object at compile time, replacing enum references directly with values.
// Defining a Const Enum
const enum SecurityZone {
Public = 1,
Staff = 2,
RestrictedAccess = 3,
Laboratories = 4,
Danger = 5
}
// Using the Const Enum
function checkPermissions(accessLevel: number, requiredZone: SecurityZone): boolean {
return accessLevel >= requiredZone;
}
// Calling with enum values
const drWuAccess = checkPermissions(5, SecurityZone.Laboratories); // true
const staffAccess = checkPermissions(2, SecurityZone.Danger); // falsePractical application of complex types
Let's look at how we can use these complex types to build a Jurassic Park management system:
// Defining interfaces and types
enum HealthStatus {
Excellent = "excellent",
Good = "good",
NeedsAttention = "needs attention",
Sick = "sick",
Critical = "critical"
}
enum DietClassification {
Herbivore = "herbivore",
Omnivore = "omnivore",
Predator = "predator"
}
interface VitalSigns {
temperature: number;
heartRate: number;
bloodPressure: [number, number]; // Tuple [systolic, diastolic]
stressLevel: number; // 1-10
}
interface Dinosaur {
id: number;
name: string;
species: string;
dietClassification: DietClassification;
age: number;
weight: number;
status: HealthStatus;
vitalSigns: VitalSigns;
dailyActivityArray: number[]; // Activity level in 3-hour periods (8 values for full day)
}
// Creating a dinosaur management system
class DinosaurManagementSystem {
private dinosaurs: Dinosaur[] = [];
addDinosaur(dino: Dinosaur): void {
this.dinosaurs.push(dino);
console.log(`Added dinosaur: ${dino.name} (${dino.species})`);
}
findDinosaur(id: number): Dinosaur | undefined {
return this.dinosaurs.find(d => d.id === id);
}
updateHealthStatus(id: number, newStatus: HealthStatus): boolean {
const dino = this.findDinosaur(id);
if (dino) {
dino.status = newStatus;
console.log(`Updated health status of ${dino.name} to: ${newStatus}`);
return true;
}
return false;
}
getPredators(): Dinosaur[] {
return this.dinosaurs.filter(d => d.dietClassification === DietClassification.Predator);
}
getDinosaursNeedingAttention(): Dinosaur[] {
return this.dinosaurs.filter(d =>
d.status === HealthStatus.NeedsAttention ||
d.status === HealthStatus.Sick ||
d.status === HealthStatus.Critical
);
}
calculateAverageActivity(id: number): number | null {
const dino = this.findDinosaur(id);
if (dino) {
const sum = dino.dailyActivityArray.reduce((acc, val) => acc + val, 0);
return sum / dino.dailyActivityArray.length;
}
return null;
}
prepareDailyReport(): [string, number, HealthStatus][] {
// Returns a tuple [name, id, status] for each dinosaur
return this.dinosaurs.map(d => [d.name, d.id, d.status]);
}
}
// Sample usage
const systemJP = new DinosaurManagementSystem();
// Adding dinosaurs to the system
systemJP.addDinosaur({
id: 1,
name: "Rexy",
species: "Tyrannosaurus Rex",
dietClassification: DietClassification.Predator,
age: 7,
weight: 8000,
status: HealthStatus.Good,
vitalSigns: {
temperature: 38.2,
heartRate: 70,
bloodPressure: [140, 90],
stressLevel: 3
},
dailyActivityArray: [2, 1, 0, 0, 1, 3, 5, 2]
});
systemJP.addDinosaur({
id: 2,
name: "Blue",
species: "Velociraptor",
dietClassification: DietClassification.Predator,
age: 3,
weight: 350,
status: HealthStatus.Excellent,
vitalSigns: {
temperature: 39.1,
heartRate: 95,
bloodPressure: [130, 85],
stressLevel: 2
},
dailyActivityArray: [4, 2, 1, 0, 2, 5, 6, 3]
});
systemJP.addDinosaur({
id: 3,
name: "Spike",
species: "Stegosaurus",
dietClassification: DietClassification.Herbivore,
age: 12,
weight: 5000,
status: HealthStatus.NeedsAttention,
vitalSigns: {
temperature: 37.5,
heartRate: 50,
bloodPressure: [125, 80],
stressLevel: 6
},
dailyActivityArray: [3, 3, 2, 1, 3, 2, 2, 1]
});
// Using the system
const predators = systemJP.getPredators();
console.log(`Number of predators in the park: ${predators.length}`);
const needingAttention = systemJP.getDinosaursNeedingAttention();
console.log(`Number of dinosaurs needing attention: ${needingAttention.length}`);
// Daily report example (array of tuples)
const dailyReport = systemJP.prepareDailyReport();
console.log("\nDaily dinosaur status report:");
dailyReport.forEach(([name, id, status]) => {
console.log(`- ${name} (ID: ${id}): ${status}`);
});
// Status update example
systemJP.updateHealthStatus(1, HealthStatus.NeedsAttention);Summary of complex types
| Type | Use in Jurassic Park | Example |
|---|---|---|
| Array | Collections of similar elements, e.g. list of dinosaurs | string[], Dinosaur[] |
| Multidimensional Array | Spatial representation, e.g. park map | number[][] |
| Tuple | Fixed structures with defined types and sizes, e.g. genetic data | [string, string, number, boolean] |
| Enum | Defined categories, e.g. threat levels | enum ThreatCategory {...} |
| Const Enum | Optimized enums for performance | const enum SecurityZone {...} |
Remember that choosing the right data types in a project is like designing safe and efficient enclosures in Jurassic Park - good design at the start saves many problems in the future!
Dr. Wu always says: "Precise control of types is the key to success - both in the genetics laboratory and in TypeScript code."
Code for this lesson: index.ts
// Complex types in Jurassic Park
console.log("TypeScript complex types\n");
// ===========================================
// 1. ARRAY - arrays
// ===========================================
console.log("=== ARRAYS ===");
// Two ways to define arrays
let dinosaurs: string[] = ["Tyrannosaurus", "Velociraptor", "Triceratops"];
let weights: Array<number> = [7500, 350, 8500, 35000];
console.log("Dinosaurs:", dinosaurs);
console.log("First dinosaur:", dinosaurs[0]);
console.log("Count:", dinosaurs.length);
// Array operations
dinosaurs.push("Spinosaurus");
console.log("After push:", dinosaurs);
// Iteration
dinosaurs.forEach((dino, index) => {
console.log(`${index + 1}. ${dino}`);
});
// Array of objects
interface Dinosaur {
id: number;
name: string;
species: string;
isCarnivore: boolean;
ageMillionYears: number;
}
const collection: Dinosaur[] = [
{ id: 1, name: "Rex", species: "Tyrannosaurus", isCarnivore: true, ageMillionYears: 68 },
{ id: 2, name: "Blue", species: "Velociraptor", isCarnivore: true, ageMillionYears: 75 },
{ id: 3, name: "Trike", species: "Triceratops", isCarnivore: false, ageMillionYears: 68 }
];
console.log("\nDinosaur collection:", collection);
// Filtering
const carnivores = collection.filter(d => d.isCarnivore);
console.log("Carnivores:", carnivores.map(d => d.name));
// ===========================================
// 2. TUPLE - tuples
// ===========================================
console.log("\n=== TUPLES ===");
// Tuple - array with fixed length and types
let dinoData: [string, number, boolean] = ["T-Rex", 8000, true];
console.log("Species:", dinoData[0]);
console.log("Weight:", dinoData[1]);
console.log("Is dangerous:", dinoData[2]);
// Tuple with named elements (TS 4.0+)
type DinoTuple = [species: string, weight: number, dangerous: boolean];
let velociraptor: DinoTuple = ["Velociraptor", 350, true];
console.log("Velociraptor data:", velociraptor);
// Tuple with optional elements
type PaddockData = [id: string, capacity: number, isLocked?: boolean];
let paddock1: PaddockData = ["P-01", 5, true];
let paddock2: PaddockData = ["P-02", 10]; // isLocked is optional
console.log("Paddock 1:", paddock1);
console.log("Paddock 2:", paddock2);
// ===========================================
// 3. ENUM - enumerations
// ===========================================
console.log("\n=== ENUM - ENUMERATIONS ===");
// Numeric enum
enum SecurityLevel {
Green = 1,
Yellow = 2,
Orange = 3,
Red = 4,
Critical = 5
}
let currentSecurity: SecurityLevel = SecurityLevel.Orange;
console.log("Security level:", SecurityLevel[currentSecurity]); // "Orange"
console.log("Security value:", currentSecurity); // 3
// String enum
enum DinosaurDiet {
Carnivore = "CARNIVORE",
Herbivore = "HERBIVORE",
Omnivore = "OMNIVORE"
}
let trexDiet: DinosaurDiet = DinosaurDiet.Carnivore;
console.log("T-Rex diet:", trexDiet); // "CARNIVORE"
// Enum with calculations
enum PaddockSize {
Small = 100,
Medium = 500,
Large = 1000,
ExtraLarge = Large * 2 // 2000
}
console.log("Extra large paddock:", PaddockSize.ExtraLarge);
// Const enum (optimization)
const enum DinosaurPeriod {
Triassic = "TRIASSIC",
Jurassic = "JURASSIC",
Cretaceous = "CRETACEOUS"
}
let trexPeriod: DinosaurPeriod = DinosaurPeriod.Cretaceous;
console.log("T-Rex period:", trexPeriod);
// ===========================================
// 4. Helper functions for complex types
// ===========================================
console.log("\n=== OPERATIONS ON COMPLEX TYPES ===");
// A function for arrays
function getTotalWeight(dinosaurs: Dinosaur[]): number {
return weights.reduce((sum, w) => sum + w, 0);
}
console.log("Total weight:", getTotalWeight(collection));
// A function for tuples
function createDinoTuple(species: string, weight: number, dangerous: boolean): DinoTuple {
return [species, weight, dangerous];
}
const newDino = createDinoTuple("Stegosaurus", 5000, false);
console.log("New dinosaur:", newDino);
// A function for enums
function getSecurityColor(level: SecurityLevel): string {
switch (level) {
case SecurityLevel.Green:
return "Green";
case SecurityLevel.Yellow:
return "Yellow";
case SecurityLevel.Orange:
return "Orange";
case SecurityLevel.Red:
return "Red";
case SecurityLevel.Critical:
return "Critical";
default:
return "Unknown";
}
}
console.log("Current security:", getSecurityColor(currentSecurity));
// ===========================================
// 5. Nested structures
// ===========================================
console.log("\n=== NESTED STRUCTURES ===");
interface Paddock {
id: string;
size: PaddockSize;
security: SecurityLevel;
dinosaurs: Dinosaur[];
coordinates: [latitude: number, longitude: number];
}
const trexPaddock: Paddock = {
id: "P-01",
size: PaddockSize.Large,
security: SecurityLevel.Critical,
dinosaurs: [collection[0]],
coordinates: [22.3964, -159.5261]
};
console.log("T-Rex Paddock:", trexPaddock);
console.log("Coordinates:", trexPaddock.coordinates);
console.log("Dinosaurs in paddock:", trexPaddock.dinosaurs.length);
// ===========================================
// 6. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Array - collections of elements of the same type");
console.log("Tuple - arrays of fixed length and different types");
console.log("Enum - named constant values");
console.log("Nesting - combining complex structures");
console.log("\nComplex types 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 is a tuple in TypeScript?
Hands-on tasks in the game
- Code editor
Define a species array (string[]) and a tuple [string, number] for the dinosaur name and weight.
- Vertical ordering
Order TypeScript types from most general to most specific:
- Horizontal ordering
Arrange the elements of a tuple declaration in TypeScript: