JavaScript and TypeScript course ยท Module 6: TypeScript Basics

Interface definitions

11 min read ยท
In this lesson11

Welcome back to Jurassic Park! Today, under the watchful eye of Dr. Henry Wu, we will explore a fundamental concept of TypeScript that is just as crucial for code organization as security protocols are for the park's proper operation - interfaces.

What are interfaces in TypeScript?

Interfaces in TypeScript define contracts in code and describe the structure of objects. They are like detailed protocols that specify what a given object should contain. In the context of Jurassic Park, interfaces can be compared to safety standards and handling protocols for different dinosaur species - each species has its own specific requirements and traits.

Basic interface syntax

We define an interface using the interface keyword:

interface Dinosaur {
  id: number;
  name: string;
  species: string;
  age: number;
  weight: number;
}

// We create an object that must satisfy the interface requirements
const rex: Dinosaur = {
  id: 1,
  name: "Rex",
  species: "Tyrannosaurus",
  age: 7,
  weight: 8000
};

// The following code would cause an error because required properties are missing
// const raptor: Dinosaur = {
//   id: 2,
//   name: "Blue"
// };

Optional properties

Some properties in an interface can be optional, marked by adding a question mark (?). It's like marking optional handling procedures for individual dinosaurs.

interface DinosaurSpecimen {
  id: number;
  name: string;
  species: string;
  rfidTag?: string;         // Optional RFID tag
  lastExamination?: Date;   // Optional date of last examination
  notes?: string;           // Optional research notes
}

// Object satisfying the interface, but without all optional properties
const specimen1: DinosaurSpecimen = {
  id: 101,
  name: "Specimen A",
  species: "Velociraptor"
};

// Object with some optional properties
const specimen2: DinosaurSpecimen = {
  id: 102,
  name: "Specimen B",
  species: "Dilophosaurus",
  rfidTag: "DILO-102",
  notes: "Shows aggressive behavior in the presence of new objects"
};

Read-only (readonly)

Some properties should only be modified when the object is created. In TypeScript we can achieve this using the readonly modifier. It's like safety procedures that, once established, cannot be changed during normal operations.

interface GeneticCode {
  readonly id: string;
  readonly sequence: string;
  readonly donorSpecies: string;
  modifications: string[];
  isolationDate: Date;
}

// Creating genetic code
const trexCode: GeneticCode = {
  id: "GEN-TREX-001",
  sequence: "ACGTTGCAAGCTA...",
  donorSpecies: "West African frog",
  modifications: ["Gap DNA filling", "Aggression gene correction"],
  isolationDate: new Date("2022-05-15")
};

// We can add new modifications
trexCode.modifications.push("Immune resistance enhancement");

// But we cannot change the values of readonly fields
// trexCode.id = "GEN-TREX-002"; // Error: Cannot assign to 'id' because it is a read-only property
// trexCode.sequence = "GCTA..."; // Error: Cannot assign to 'sequence' because it is a read-only property

Function interfaces

Interfaces can also define function types, which is useful when describing callbacks or functions passed as parameters. In the context of the park, it's like defining standard procedures for handling different situations.

// Security check function interface
interface SecurityCheck {
  (threatLevel: number, parkZone: string): boolean;
}

// Implementation of a function conforming to the interface
const checkAccess: SecurityCheck = function(level, zone) {
  // Access checking logic
  if (zone === "T-Rex Enclosure" && level < 5) {
    return false; // Deny access to T-Rex zone for staff below level 5
  }

  if (zone.includes("Laboratory") && level < 4) {
    return false; // Deny access to laboratories for staff below level 4
  }

  return true; // Access permitted for other cases
};

// Using the function
console.log(checkAccess(3, "T-Rex Enclosure")); // false
console.log(checkAccess(5, "T-Rex Enclosure")); // true
console.log(checkAccess(3, "Public area")); // true

Indexable types

Interfaces can define indexable types - useful when we have objects with a dynamic number of properties of the same type. In the context of the park, this could be a dinosaur database indexed by their identifiers.

// Interface for a dinosaur database
interface DinosaursDatabase {
  [id: string]: {
    name: string;
    species: string;
    age: number;
    health: "good" | "needs attention" | "critical";
  };
}

// Creating the database
const database: DinosaursDatabase = {
  "TREX-001": {
    name: "Rex",
    species: "Tyrannosaurus",
    age: 7,
    health: "good"
  },
  "VELOC-001": {
    name: "Blue",
    species: "Velociraptor",
    age: 4,
    health: "good"
  },
  "TRIC-003": {
    name: "Trike",
    species: "Triceratops",
    age: 10,
    health: "needs attention"
  }
};

// Accessing data
console.log(database["VELOC-001"].name); // "Blue"

// Adding a new entry
database["STEGO-002"] = {
  name: "Spike",
  species: "Stegosaurus",
  age: 6,
  health: "good"
};

Class interfaces

Interfaces can also define contracts that classes must implement. It's like operational standards that every department in the park must meet.

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

  activate(): void;
  deactivate(): void;
  checkStatus(): string;
}

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

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

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

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

  checkStatus(): string {
    return this.isActive
      ? `${this.name}: ACTIVE (Level ${this.securityLevel})`
      : `${this.name}: INACTIVE`;
  }

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

// Using the class
const trexFence = new ElectronicFenceSystem("T-Rex Fence", 5, 10000);
trexFence.activate();
console.log(trexFence.checkStatus());
trexFence.increaseVoltage(2000);

Extending interfaces

Interfaces can extend other interfaces, similar to how in biology species share common traits but also have their own unique properties.

// Basic interface for all animals in the park
interface Animal {
  id: number;
  species: string;
  age: number;
  weight: number;
}

// Interface for dinosaurs extending the Animal interface
interface Dinosaur extends Animal {
  era: string; // e.g. "Cretaceous", "Jurassic"
  isPredator: boolean;
  mainDiet: string[];
}

// Interface for predatory dinosaurs extending the Dinosaur interface
interface PredatoryDinosaur extends Dinosaur {
  biteForce: number;  // in PSI
  runSpeed: number;   // in km/h
  huntingBehavior: string[];
}

// Creating an object conforming to the PredatoryDinosaur interface
const velociraptor: PredatoryDinosaur = {
  id: 101,
  species: "Velociraptor",
  age: 4,
  weight: 70,
  era: "Cretaceous",
  isPredator: true,
  mainDiet: ["small mammals", "lizards", "other small dinosaurs"],
  biteForce: 1000,
  runSpeed: 60,
  huntingBehavior: ["pack hunting", "ambush", "chase"]
};

Declaration merging for interfaces

In TypeScript it is possible to define the same interface multiple times - the declarations will be merged. This is useful when we want to add new properties to an existing interface.

// Initial definition of the security protocol
interface SecurityProtocol {
  name: string;
  threatLevel: number;
  evacuationProcedure: string;
}

// Extending the protocol with additional properties
interface SecurityProtocol {
  responsibleStaff: string[];
  responseTime: number; // in minutes
}

// The object must contain all properties from both declarations
const alphaProtocol: SecurityProtocol = {
  name: "Protocol Alpha",
  threatLevel: 3,
  evacuationProcedure: "Evacuation towards the main control center",
  responsibleStaff: ["Dr. Wu", "Owen Grady", "Claire Dearing"],
  responseTime: 15
};

Interfaces vs types

TypeScript also offers the type keyword for defining types. Although in many cases interfaces and types can be used interchangeably, there are differences between them:

// Definition using interface
interface EvacuationPlan {
  route: string[];
  estimatedTime: number;
  assemblyPoints: string[];
}

// Equivalent definition using type
type EvacuationPlanType = {
  route: string[];
  estimatedTime: number;
  assemblyPoints: string[];
};

// Both work similarly for basic use
const planA: EvacuationPlan = {
  route: ["Operations center", "Main Street", "Evacuation hall"],
  estimatedTime: 25,
  assemblyPoints: ["Operations center", "Evacuation hall"]
};

const planB: EvacuationPlanType = {
  route: ["Gallimimus Enclosure", "Innovation Center", "Evacuation hall"],
  estimatedTime: 30,
  assemblyPoints: ["Innovation Center", "Evacuation hall"]
};

Key differences between interface and type:

  1. Extensibility:

    • Interfaces can be extended by multiple declarations with the same name
    • Types cannot be "opened" - once declared, a type cannot be extended
  2. Complex types:

    • Types can directly represent primitive types, unions, intersections
    • Interfaces are more focused on defining the shape of objects
// Only possible with types
type DinosaurID = string | number;
type EnclosureCoordinates = [number, number, string]; // Tuple
type DinosaurStatus = "active" | "resting" | "sleeping"; // Union of literals

// More natural with interfaces
interface Procedure {
  name: string;
  steps: string[];
  executionTime: number;
  responsibleStaff: string[];
}

Practical application of interfaces

Let's look at how we can use interfaces to model the Jurassic Park management system:

// Basic interfaces
interface ParkPerson {
  id: string;
  firstName: string;
  lastName: string;
  accessLevel: 1 | 2 | 3 | 4 | 5;
  hireDate: Date;
}

interface Location {
  id: string;
  name: string;
  type: "enclosure" | "laboratory" | "operations center" | "public zone";
  coordinates: [number, number]; // [latitude, longitude]
  requiredAccessLevel: 1 | 2 | 3 | 4 | 5;
}

interface DinosaurSpecies {
  name: string;
  geologicalEra: string;
  type: "herbivore" | "predator" | "omnivore";
  averageWeight: number;
  averageAge: number;
  dangerLevel: 1 | 2 | 3 | 4 | 5;
  dietRequirements: string[];
  habitatRequirements: string[];
}

interface DinosaurSpecimen {
  id: string;
  species: string;
  firstName?: string;
  age: number;
  weight: number;
  gender: "male" | "female";
  location: string; // Location ID
  healthStatus: "excellent" | "good" | "needs attention" | "sick" | "critical";
  lastExamination: Date;
  rfidTag: string;
  notes?: string;
}

// Interfaces for management systems
interface SpecimenTrackingSystem {
  getPosition(specimenId: string): [number, number];
  trackMovement(specimenId: string, trackingTime: number): [number, number][];
  checkIfInZone(specimenId: string, zoneId: string): boolean;
  alertWhenOutsideZone(specimenId: string, callback: (specimen: DinosaurSpecimen) => void): void;
}

interface EmployeeManagementSystem {
  addEmployee(employee: ParkPerson): void;
  removeEmployee(id: string): boolean;
  grantAccess(employeeId: string, level: 1 | 2 | 3 | 4 | 5): boolean;
  checkPresenceInZone(employeeId: string, zoneId: string): boolean;
}

// Example implementation
class ParkManagementSystem {
  private employees: ParkPerson[] = [];
  private locations: Location[] = [];
  private species: DinosaurSpecies[] = [];
  private specimens: DinosaurSpecimen[] = [];

  // Methods for staff
  addEmployee(employee: ParkPerson): void {
    this.employees.push(employee);
    console.log(`Added employee: ${employee.firstName} ${employee.lastName}`);
  }

  // Methods for locations
  addLocation(location: Location): void {
    this.locations.push(location);
    console.log(`Added location: ${location.name}`);
  }

  // Methods for species
  addSpecies(species: DinosaurSpecies): void {
    this.species.push(species);
    console.log(`Added species: ${species.name}`);
  }

  // Methods for specimens
  addSpecimen(specimen: DinosaurSpecimen): void {
    this.specimens.push(specimen);
    console.log(`Added specimen: ${specimen.id} (${specimen.species})`);
  }

  // Management methods
  checkAccess(employeeId: string, locationId: string): boolean {
    const employee = this.employees.find(p => p.id === employeeId);
    const location = this.locations.find(l => l.id === locationId);

    if (!employee || !location) return false;

    return employee.accessLevel >= location.requiredAccessLevel;
  }

  findSpecimensBySpecies(speciesName: string): DinosaurSpecimen[] {
    return this.specimens.filter(o => o.species === speciesName);
  }

  findSpecimensInZone(zoneId: string): DinosaurSpecimen[] {
    return this.specimens.filter(o => o.location === zoneId);
  }

  generateParkStatusReport(): {
    employeeCount: number;
    locationCount: number;
    speciesCount: number;
    specimenCount: number;
    specimenHealthStatus: {
      excellent: number;
      good: number;
      needsAttention: number;
      sick: number;
      critical: number;
    }
  } {
    // Analyzing health status of all specimens
    const healthStatus = {
      excellent: 0,
      good: 0,
      needsAttention: 0,
      sick: 0,
      critical: 0
    };

    this.specimens.forEach(specimen => {
      if (specimen.healthStatus === "excellent") healthStatus.excellent++;
      else if (specimen.healthStatus === "good") healthStatus.good++;
      else if (specimen.healthStatus === "needs attention") healthStatus.needsAttention++;
      else if (specimen.healthStatus === "sick") healthStatus.sick++;
      else if (specimen.healthStatus === "critical") healthStatus.critical++;
    });

    return {
      employeeCount: this.employees.length,
      locationCount: this.locations.length,
      speciesCount: this.species.length,
      specimenCount: this.specimens.length,
      specimenHealthStatus: healthStatus
    };
  }
}

// Example usage
const jurassicPark = new ParkManagementSystem();

// Adding a location
jurassicPark.addLocation({
  id: "LOC-001",
  name: "T-Rex Enclosure",
  type: "enclosure",
  coordinates: [23.45, -67.89],
  requiredAccessLevel: 4
});

// Adding a species
jurassicPark.addSpecies({
  name: "Tyrannosaurus Rex",
  geologicalEra: "Cretaceous",
  type: "predator",
  averageWeight: 7000,
  averageAge: 30,
  dangerLevel: 5,
  dietRequirements: ["large amounts of meat", "calcium supplementation"],
  habitatRequirements: ["large area", "natural vegetation", "water access"]
});

// Adding an employee
jurassicPark.addEmployee({
  id: "EMP-001",
  firstName: "Owen",
  lastName: "Grady",
  accessLevel: 5,
  hireDate: new Date("2010-06-15")
});

// Adding a specimen
jurassicPark.addSpecimen({
  id: "DINO-001",
  species: "Tyrannosaurus Rex",
  firstName: "Rexy",
  age: 7,
  weight: 7500,
  gender: "female",
  location: "LOC-001",
  healthStatus: "good",
  lastExamination: new Date("2023-03-20"),
  rfidTag: "RFID-TREX-001"
});

// Generating a report
const report = jurassicPark.generateParkStatusReport();
console.log("Jurassic Park Status Report:");
console.log(`Number of employees: ${report.employeeCount}`);
console.log(`Number of locations: ${report.locationCount}`);
console.log(`Number of species: ${report.speciesCount}`);
console.log(`Number of specimens: ${report.specimenCount}`);
console.log("Specimen health status:", report.specimenHealthStatus);

Summary

Interfaces in TypeScript are a powerful tool for modeling data structures and defining contracts in code. In the context of managing Jurassic Park, they allow us to precisely define what the various systems, procedures and park elements should look like.

Interface featureUse in Jurassic Park
Basic definitionData structures for dinosaurs, employees, locations
Optional propertiesAdditional information that may or may not be available
Readonly propertiesData that should not be changed, e.g. genetic IDs
Function interfacesDefinitions of safety procedures and protocols
Indexable typesDynamic databases of dinosaurs and resources
Class interfacesStandards for security and monitoring systems
Extending interfacesInheritance of traits between dinosaur species
Declaration mergingExtending protocols with additional procedures

Dr. Wu summarizes: "Interfaces in TypeScript, like our park protocols, ensure that every element of the system works as expected. They allow us to build complex systems with confidence that individual components will work together - which is absolutely crucial when dealing with species that can be dangerous if something goes wrong."

Code for this lesson: index.ts
// Interfaces in Jurassic Park
console.log("TypeScript interfaces\n");

// ===========================================
// 1. Basic interfaces
// ===========================================
console.log("=== BASIC INTERFACES ===");

// A simple interface
interface Dinosaur {
  name: string;
  species: string;
  age: number;
  weight: number;
}

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

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

// ===========================================
// 2. Optional properties
// ===========================================
console.log("\n=== OPTIONAL PROPERTIES ===");

interface DinosaurWithOptionals {
  name: string;
  species: string;
  age: number;
  nickname?: string; // optional
  medicalNotes?: string; // optional
}

const blue: DinosaurWithOptionals = {
  name: "Blue",
  species: "Velociraptor",
  age: 3,
  nickname: "The Beta"
  // medicalNotes omitted - OK
};

console.log("Blue:", blue);
console.log("Has medical notes:", blue.medicalNotes !== undefined);

// ===========================================
// 3. Readonly properties
// ===========================================
console.log("\n=== READONLY PROPERTIES ===");

interface DinosaurWithReadonly {
  readonly id: string; // cannot be changed
  readonly dnaSequence: string; // cannot be changed
  name: string; // can be changed
  age: number; // can be changed
}

const dino: DinosaurWithReadonly = {
  id: "DINO-001",
  dnaSequence: "ACGT...",
  name: "Rex",
  age: 5
};

// dino.id = "DINO-002"; // Error: Cannot assign to 'id'
dino.name = "Rexy"; // OK
dino.age = 6; // OK

console.log("Dinosaur:", dino);

// ===========================================
// 4. Methods in interfaces
// ===========================================
console.log("\n=== METHODS IN INTERFACES ===");

interface DinosaurWithMethods {
  name: string;
  species: string;
  energy: number;

  // Methods
  roar(): string;
  eat(amount: number): void;
  sleep(hours: number): void;
  getStatus(): string;
}

class TyrannosaurusRex implements DinosaurWithMethods {
  name: string;
  species: string;
  energy: number;

  constructor(name: string) {
    this.name = name;
    this.species = "Tyrannosaurus Rex";
    this.energy = 100;
  }

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

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

  getStatus(): string {
    if (this.energy > 70) return "Energetic";
    if (this.energy > 30) return "Normal";
    return "Tired";
  }
}

const rexy = new TyrannosaurusRex("Rexy");
console.log(rexy.roar());
rexy.eat(50);
console.log("Status:", rexy.getStatus());

// ===========================================
// 5. Index signatures
// ===========================================
console.log("\n=== INDEX SIGNATURES ===");

// Dynamic keys
interface DinosaurCollection {
  [id: string]: Dinosaur;
}

const collection: DinosaurCollection = {
  "T-001": trex,
  "V-001": blue
};

console.log("Collection:", collection);
console.log("T-001:", collection["T-001"]);

// Mixed properties
interface PaddockData {
  id: string;
  capacity: number;
  [key: string]: any; // other dynamic properties
}

const paddock: PaddockData = {
  id: "P-01",
  capacity: 10,
  securityLevel: "high",
  temperature: 25,
  humidity: 60
};

console.log("Paddock:", paddock);

// ===========================================
// 6. Functions in interfaces
// ===========================================
console.log("\n=== FUNCTIONS IN INTERFACES ===");

// Function type
interface DinosaurFilter {
  (dino: Dinosaur): boolean;
}

const carnivoreFilter: DinosaurFilter = (dino) => {
  return dino.species.includes("saurus") && dino.weight > 1000;
};

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

// Interface for functions with properties
interface DinosaurValidator {
  (dino: Dinosaur): boolean;
  errorMessage: string;
}

const ageValidator: DinosaurValidator = (dino) => {
  return dino.age >= 0 && dino.age <= 100;
};
ageValidator.errorMessage = "Age must be between 0 and 100";

console.log("Validator:", ageValidator(trex));
console.log("Error message:", ageValidator.errorMessage);

// ===========================================
// 7. Nested interfaces
// ===========================================
console.log("\n=== NESTED INTERFACES ===");

interface Location {
  latitude: number;
  longitude: number;
  altitude: number;
}

interface Paddock {
  id: string;
  name: string;
  location: Location; // nested interface
  dimensions: {
    width: number;
    length: number;
    height: number;
  };
  dinosaurs: Dinosaur[];
}

const trexPaddock: Paddock = {
  id: "P-01",
  name: "T-Rex Territory",
  location: {
    latitude: 22.3964,
    longitude: -159.5261,
    altitude: 50
  },
  dimensions: {
    width: 1000,
    length: 1500,
    height: 50
  },
  dinosaurs: [trex]
};

console.log("Paddock:", trexPaddock);
console.log("Location:", trexPaddock.location);

// ===========================================
// 8. Hybrid types
// ===========================================
console.log("\n=== HYBRID TYPES ===");

interface Counter {
  (start: number): string;
  interval: number;
  reset(): void;
}

function createCounter(): Counter {
  let count = 0;

  const counter = function(start: number) {
    count = start;
    return `Count: ${count}`;
  } as Counter;

  counter.interval = 1;
  counter.reset = function() {
    count = 0;
  };

  return counter;
}

const myCounter = createCounter();
console.log(myCounter(5));
console.log("Interval:", myCounter.interval);
myCounter.reset();

// ===========================================
// 9. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Basic interfaces - object structure");
console.log("Optional properties - ?");
console.log("Readonly - immutable properties");
console.log("Methods - functions in interfaces");
console.log("Index signatures - dynamic keys");
console.log("Nested interfaces - complex structures");

console.log("\nInterfaces 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. 1. How does an interface differ from a type alias in TypeScript?

  2. 2. How do you mark an interface property as optional in TypeScript?

Hands-on tasks in the game

  • Code editor

    Define a Dinosaur interface with fields name: string, species: string, weight?: number and a method roar(): void.

  • Horizontal ordering

    Arrange the elements of a TypeScript interface definition:

  • Click in order

    Arrange the elements of a readonly field definition in an interface:

  • Vertical ordering

    Order interface concepts from simplest to most advanced:

  1. QuestionTypeScript Interfaces
  2. QuestionOptional Interface Properties
  3. Coding taskPractice: Creating an Interface
  4. Put in orderInterface Syntax
  5. Click in orderSorting: readonly Field in an Interface
  6. Put in orderTypeScript Interface Capabilities

Useful articles