JavaScript and TypeScript course ยท Module 10: TypeScript in Practice

Final Project: Jurassic Park Diagnostic System

11 min read ยท
In this lesson4

"We've reached the end of our journey," announces Dr. Ellie Sattler, standing in InGen's main diagnostic laboratory. "Throughout this module, you've mastered Web Workers, memory management, advanced TypeScript types - from utility types, through conditional and mapped types, to template literal types and module augmentation. You've also learned Test-Driven Development and TypeScript integration with popular frameworks."

"Now you'll build a complete Jurassic Park diagnostic system - a project that combines all these skills into one cohesive system. Think of it as a simulation of real, production code that could run in our park."

In this project, you'll create an advanced diagnostic system combining: expert-level typing with utility types and conditional types, template literal types for API generation, mapped types for data transformation, module augmentation for extending existing libraries, and a TDD approach with unit tests.

Project Goal

You'll build a DiagnosticCenter system that:

  • Uses advanced utility types for precise data modeling
  • Applies conditional types for automatic diagnostic strategy selection
  • Uses template literal types for building a type-safe API
  • Implements mapped types for diagnostic data transformation
  • Extends existing modules through module augmentation
  • Is written using a TDD approach with unit tests

Functional Requirements

1. Advanced Utility Types for Diagnostic Data

Define precise data types, using both built-in and custom utility types. The system must support different dinosaur categories with different sets of diagnostic parameters.

// Base dinosaur type
interface DinosaurRecord {
  id: string;
  species: string;
  name: string;
  age: number;
  weight: number;
  height: number;
  enclosureId: string;
  diet: 'carnivore' | 'herbivore' | 'omnivore';
  healthStatus: 'healthy' | 'sick' | 'critical' | 'quarantined';
  lastCheckup: Date;
  geneticModifications: string[];
  dangerRating: 1 | 2 | 3 | 4 | 5;
}

// Custom utility types
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? T[K] extends Date | Array<any>
      ? T[K]
      : DeepReadonly<T[K]>
    : T[K];
};

type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
  Pick<T, Exclude<keyof T, Keys>> &
  { [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>> }[Keys];

type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

// Locked record - cannot be modified after closing diagnostics
type LockedDiagnosticRecord = DeepReadonly<DinosaurRecord>;

// Update - require at least one field
type DinosaurUpdate = RequireAtLeastOne<
  Partial<Pick<DinosaurRecord, 'healthStatus' | 'weight' | 'enclosureId' | 'dangerRating'>>,
  'healthStatus' | 'weight' | 'enclosureId' | 'dangerRating'
>;

// Display record - convert Date to string
type DisplayRecord<T> = {
  [K in keyof T]: T[K] extends Date ? string : T[K];
};

type DinosaurDisplayRecord = DisplayRecord<DinosaurRecord>;

// Filtering numeric fields
type NumericFields<T> = {
  [K in keyof T as T[K] extends number ? K : never]: T[K];
};

type DinosaurMetrics = NumericFields<DinosaurRecord>;
// Result: { age: number; weight: number; height: number; dangerRating: 1|2|3|4|5 }

2. Conditional Types for Diagnostic Strategies

Use conditional types to automatically determine the diagnostic procedure based on the dinosaur's species and health status. The system must "know" at the type level what tests to perform.

// Species types
type CarnivoreSpecies = 'TRex' | 'Velociraptor' | 'Spinosaurus' | 'Dilophosaurus';
type HerbivoreSpecies = 'Triceratops' | 'Brachiosaurus' | 'Stegosaurus' | 'Parasaurolophus';
type FlyingSpecies = 'Pteranodon' | 'Dimorphodon';
type AquaticSpecies = 'Mosasaurus' | 'Plesiosaurus';

type AllSpecies = CarnivoreSpecies | HerbivoreSpecies | FlyingSpecies | AquaticSpecies;

// Conditional type - diagnostic procedure depends on species
type DiagnosticProcedure<S extends AllSpecies> =
  S extends CarnivoreSpecies ? {
    type: 'carnivore-diagnostic';
    sedationRequired: true;
    aggressionTest: boolean;
    teethInspection: boolean;
    clawMeasurement: boolean;
    huntingBehaviorAnalysis: boolean;
  } :
  S extends HerbivoreSpecies ? {
    type: 'herbivore-diagnostic';
    sedationRequired: false;
    digestiveAnalysis: boolean;
    hoofInspection: boolean;
    grazingPatternCheck: boolean;
  } :
  S extends FlyingSpecies ? {
    type: 'flying-diagnostic';
    sedationRequired: true;
    wingspanMeasurement: number;
    flightCapabilityTest: boolean;
    nestInspection: boolean;
  } :
  S extends AquaticSpecies ? {
    type: 'aquatic-diagnostic';
    sedationRequired: true;
    underwaterExam: boolean;
    gillFunction: boolean;
    divingDepthTest: number;
  } :
  never;

// Diagnostic result - depends on the procedure
type DiagnosticResult<S extends AllSpecies> = {
  species: S;
  procedure: DiagnosticProcedure<S>;
  timestamp: Date;
  veterinarian: string;
  passed: boolean;
  notes: string;
};

// Usage - TypeScript enforces the correct fields
const trexDiagnostic: DiagnosticResult<'TRex'> = {
  species: 'TRex',
  procedure: {
    type: 'carnivore-diagnostic',
    sedationRequired: true,
    aggressionTest: true,
    teethInspection: true,
    clawMeasurement: true,
    huntingBehaviorAnalysis: false
  },
  timestamp: new Date(),
  veterinarian: 'Dr. Harding',
  passed: true,
  notes: 'T-Rex in excellent condition. Sedation went smoothly.'
};

// Conditional type with infer - extract the procedure type
type ExtractProcedureType<T> =
  T extends DiagnosticResult<infer S>
    ? DiagnosticProcedure<S>
    : never;

// Distributive conditional type - filtering species requiring sedation
type RequiresSedation<S extends AllSpecies> =
  DiagnosticProcedure<S> extends { sedationRequired: true } ? S : never;

type SedatedSpecies = RequiresSedation<AllSpecies>;
// Result: 'TRex' | 'Velociraptor' | ... (all requiring sedation)

3. Template Literal Types for Type-safe API

Create an API system that guarantees correctness of endpoint names, configuration keys, and diagnostic messages at the type level.

// Template literal types for API endpoints
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiVersion = 'v1' | 'v2';
type Resource = 'dinosaurs' | 'enclosures' | 'diagnostics' | 'alerts';

// Automatic API path generation
type ApiEndpoint = `/api/${ApiVersion}/${Resource}`;
// Result: "/api/v1/dinosaurs" | "/api/v1/enclosures" | ... (12 combinations)

type ApiEndpointWithId = `${ApiEndpoint}/${string}`;

// Template literal types for configuration keys
type SensorType = 'temperature' | 'heartRate' | 'movement' | 'stress';
type SensorLocation = 'head' | 'body' | 'tail' | 'legs';

type SensorConfigKey = `sensor_${SensorType}_${SensorLocation}`;
// Result: "sensor_temperature_head" | "sensor_temperature_body" | ... (16 combinations)

type SensorConfig = Record<SensorConfigKey, {
  enabled: boolean;
  threshold: number;
  interval: number;
}>;

// Template literal types for diagnostic messages
type DiagnosticStatus = 'started' | 'completed' | 'failed' | 'cancelled';
type DiagnosticMessage<S extends AllSpecies, D extends DiagnosticStatus> =
  `[DIAGNOSTIC] Species: ${S} | Status: ${D}`;

// Usage
const message: DiagnosticMessage<'TRex', 'completed'> =
  '[DIAGNOSTIC] Species: TRex | Status: completed';

// Extraction from template literal type
type ExtractSpecies<T> = T extends `[DIAGNOSTIC] Species: ${infer S} | Status: ${string}`
  ? S
  : never;

type ExtractedSpecies = ExtractSpecies<typeof message>; // "TRex"

// Advanced: converting camelCase to kebab-case
type CamelToKebab<S extends string> =
  S extends `${infer First}${infer Rest}`
    ? Rest extends Uncapitalize<Rest>
      ? `${Lowercase<First>}${CamelToKebab<Rest>}`
      : `${Lowercase<First>}-${CamelToKebab<Rest>}`
    : S;

type TestKebab = CamelToKebab<'healthStatus'>; // "health-status"
type TestKebab2 = CamelToKebab<'dangerRating'>; // "danger-rating"

4. Mapped Types for Transformation and Type Generation

Use mapped types to automatically generate forms, validators, and diagnostic data transformations.

// Mapped type: generate form type from data model
type FormFields<T> = {
  [K in keyof T]: {
    value: T[K];
    label: string;
    required: boolean;
    validate: (value: T[K]) => boolean;
  };
};

type DinosaurForm = FormFields<Pick<DinosaurRecord, 'name' | 'species' | 'weight' | 'healthStatus'>>;

// Mapped type: generate validator type
type Validators<T> = {
  [K in keyof T as `validate${Capitalize<K & string>}`]: (value: T[K]) => boolean;
};

type DinosaurValidators = Validators<Pick<DinosaurRecord, 'name' | 'age' | 'weight'>>;
// Result: {
//   validateName: (value: string) => boolean;
//   validateAge: (value: number) => boolean;
//   validateWeight: (value: number) => boolean;
// }

// Mapped type: generate getters and setters
type Accessors<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
} & {
  [K in keyof T as `set${Capitalize<K & string>}`]: (value: T[K]) => void;
};

type DinosaurAccessors = Accessors<Pick<DinosaurRecord, 'name' | 'healthStatus'>>;
// Result: {
//   getName: () => string;
//   setName: (value: string) => void;
//   getHealthStatus: () => 'healthy' | 'sick' | 'critical' | 'quarantined';
//   setHealthStatus: (value: ...) => void;
// }

// Mapped type: convert values to Observable
type Observable<T> = {
  [K in keyof T]: {
    value: T[K];
    subscribe: (callback: (newValue: T[K], oldValue: T[K]) => void) => void;
    unsubscribe: (callback: Function) => void;
  };
};

type ObservableDinosaurMetrics = Observable<DinosaurMetrics>;

// Mapped type implementation at runtime
function createValidators<T extends Record<string, any>>(
  rules: { [K in keyof T]: (value: T[K]) => boolean }
): Validators<T> {
  const validators = {} as any;
  for (const key in rules) {
    const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
    validators[`validate${capitalizedKey}`] = rules[key];
  }
  return validators;
}

// Usage example
const dinoValidators = createValidators<Pick<DinosaurRecord, 'name' | 'age' | 'weight'>>({
  name: (value) => value.length >= 2 && value.length <= 50,
  age: (value) => value > 0 && value < 200,
  weight: (value) => value > 0 && value < 100000
});

5. Module Augmentation and Test-Driven Development

Extend existing types through module augmentation and write the system using a TDD approach - tests first, then implementation.

// Module augmentation - extending an existing module
declare module './dinosaur-record' {
  interface DinosaurRecord {
    lastDiagnosticId?: string;
    diagnosticHistory: DiagnosticEntry[];
    riskScore: number;
  }
}

interface DiagnosticEntry {
  id: string;
  date: Date;
  type: string;
  result: 'pass' | 'fail' | 'inconclusive';
  veterinarian: string;
}

// TDD - write tests first
// Test 1: DiagnosticCenter should calculate risk
function testCalculateRiskScore() {
  const center = new DiagnosticCenter();

  // Healthy herbivore - low risk
  const herbivoreRisk = center.calculateRiskScore({
    diet: 'herbivore',
    healthStatus: 'healthy',
    dangerRating: 1,
    age: 5
  } as DinosaurRecord);

  console.assert(herbivoreRisk < 30,
    `Expected risk < 30, got ${herbivoreRisk}`);

  // Sick carnivore - high risk
  const carnivoreRisk = center.calculateRiskScore({
    diet: 'carnivore',
    healthStatus: 'sick',
    dangerRating: 5,
    age: 12
  } as DinosaurRecord);

  console.assert(carnivoreRisk > 70,
    `Expected risk > 70, got ${carnivoreRisk}`);

  console.log('testCalculateRiskScore: PASSED');
}

// Test 2: System should filter dinosaurs requiring checkup
function testFilterDinosRequiringCheckup() {
  const center = new DiagnosticCenter();

  const dinosaurs: Partial<DinosaurRecord>[] = [
    { name: 'Rex', lastCheckup: new Date('2024-01-01'), healthStatus: 'healthy' },
    { name: 'Blue', lastCheckup: new Date('2025-12-01'), healthStatus: 'healthy' },
    { name: 'Echo', lastCheckup: new Date('2025-12-15'), healthStatus: 'critical' }
  ];

  const needCheckup = center.filterRequiringCheckup(
    dinosaurs as DinosaurRecord[],
    30 // Days since last checkup
  );

  // Rex - checkup more than 30 days ago
  // Echo - "critical" status requires immediate checkup
  console.assert(needCheckup.length === 2,
    `Expected 2 dinosaurs, got ${needCheckup.length}`);

  console.log('testFilterDinosRequiringCheckup: PASSED');
}

// Test 3: Report generation should return the correct format
function testGenerateReport() {
  const center = new DiagnosticCenter();

  const report = center.generateReport('TRex', {
    species: 'TRex',
    procedure: {
      type: 'carnivore-diagnostic',
      sedationRequired: true,
      aggressionTest: true,
      teethInspection: true,
      clawMeasurement: true,
      huntingBehaviorAnalysis: false
    },
    timestamp: new Date(),
    veterinarian: 'Dr. Harding',
    passed: true,
    notes: 'Examination completed successfully'
  });

  console.assert(report.includes('[DIAGNOSTIC]'),
    'Report should contain [DIAGNOSTIC] header');
  console.assert(report.includes('TRex'),
    'Report should contain species');
  console.assert(report.includes('Dr. Harding'),
    'Report should contain veterinarian');

  console.log('testGenerateReport: PASSED');
}

// Implementation (after writing tests)
class DiagnosticCenter {
  calculateRiskScore(dino: Pick<DinosaurRecord, 'diet' | 'healthStatus' | 'dangerRating' | 'age'>): number {
    let score = 0;

    // Diet affects base risk
    const dietScores = { carnivore: 30, omnivore: 15, herbivore: 5 };
    score += dietScores[dino.diet];

    // Health status
    const healthScores = { healthy: 0, sick: 20, critical: 40, quarantined: 30 };
    score += healthScores[dino.healthStatus];

    // Danger level (1-5) * 6
    score += dino.dangerRating * 6;

    // Age - older dinosaurs are more unpredictable
    if (dino.age > 10) score += 10;

    return Math.min(100, Math.max(0, score));
  }

  filterRequiringCheckup(dinosaurs: DinosaurRecord[], maxDaysSinceCheckup: number): DinosaurRecord[] {
    const now = new Date();
    return dinosaurs.filter(dino => {
      // Critical status - always requires checkup
      if (dino.healthStatus === 'critical') return true;

      // Check time since last checkup
      const daysSinceCheckup = Math.floor(
        (now.getTime() - dino.lastCheckup.getTime()) / (1000 * 60 * 60 * 24)
      );
      return daysSinceCheckup > maxDaysSinceCheckup;
    });
  }

  generateReport<S extends AllSpecies>(
    species: S,
    result: DiagnosticResult<S>
  ): string {
    return [
      `[DIAGNOSTIC] Species: ${species} | Status: ${result.passed ? 'completed' : 'failed'}`,
      `Veterinarian: ${result.veterinarian}`,
      `Date: ${result.timestamp.toISOString()}`,
      `Result: ${result.passed ? 'POSITIVE' : 'NEGATIVE'}`,
      `Notes: ${result.notes}`
    ].join('\n');
  }
}

// Running tests
testCalculateRiskScore();
testFilterDinosRequiringCheckup();
testGenerateReport();

Implementation Guidelines

Start by defining base types and interfaces - this is the foundation of your diagnostic system. Then build conditional types for diagnostic procedures, template literal types for the API, and mapped types for transformations. Finally, write tests and implement the DiagnosticCenter.

Suggested implementation order:

// 1. Base types: DinosaurRecord, AllSpecies
// 2. Utility types: DeepReadonly, RequireAtLeastOne, NumericFields
// 3. Conditional types: DiagnosticProcedure<S>, DiagnosticResult<S>
// 4. Template literal types: ApiEndpoint, SensorConfigKey
// 5. Mapped types: FormFields, Validators, Accessors
// 6. Module augmentation: extending DinosaurRecord
// 7. Unit tests (TDD)
// 8. DiagnosticCenter implementation
// 9. Integration and running tests

Remember the key principles:

  • Utility types are for transforming existing types - don't create new types from scratch when you can transform existing ones
  • Conditional types with infer allow extracting types from nested structures
  • Template literal types guarantee string correctness at compile time
  • Mapped types with as allow key name remapping
  • Module augmentation requires declare module and merges with the original type
  • TDD means: write test -> run (red) -> implement -> run (green) -> refactor

Good Luck!

"Remember," says Dr. Sattler with a smile, "in Jurassic Park there is no room for type errors. Every any is a potential security breach, every missing type is an open enclosure gate. TypeScript gives you the tools to catch 90% of bugs before the code even runs. Utility types, conditional types, mapped types, template literal types - these are your arsenal. Use them wisely."

"And tests? Tests are like alarm systems in enclosures. You don't build them after the T-Rex escapes. You build them BEFORE that happens. TDD is a philosophy that protects your code from catastrophe."

Open your editor and build your diagnostic system - complete, fully typed, and tested!

Code for this lesson: index.ts
// Final project: Jurassic Park diagnostic system
// Combine: utility types, conditional types, mapped types, template literal types, TDD

// === 1. ADVANCED UTILITY TYPES ===
interface DinosaurRecord {
  id: string;
  species: string;
  name: string;
  age: number;
  weight: number;
  diet: "carnivore" | "herbivore" | "omnivore";
  healthStatus: "healthy" | "sick" | "critical";
  enclosureId: string;
  dangerRating: 1 | 2 | 3 | 4 | 5;
}

// TODO: Create DeepReadonly<T> - recursive readonly
type DeepReadonly<T> = {
  // TODO: Use mapped types with a condition for nested objects
  readonly [K in keyof T]: T[K];
};

// TODO: Create RequireAtLeastOne<T> - requires at least one field
// TODO: Create Mutable<T> - removes readonly from fields

// === 2. CONDITIONAL TYPES ===
// TODO: Create a DiagnosticStrategy<T> type
// If diet = "carnivore" -> requires: bitePressureTest, aggressionLevel
// If diet = "herbivore" -> requires: foliagePreference, migrationPattern
type DiagnosticStrategy<T extends DinosaurRecord["diet"]> =
  // TODO: Implement the condition
  T extends "carnivore" ? { bitePressureTest: number; aggressionLevel: number }
  : { foliagePreference: string[]; migrationPattern: string };

// === 3. TEMPLATE LITERAL TYPES ===
// TODO: Create type-safe API endpoints
type Endpoint = "dinosaurs" | "enclosures" | "alerts";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

// TODO: Create an ApiRoute type = "${HttpMethod} /api/${Endpoint}"
// TODO: Create a handleRequest(route: ApiRoute): void function

// === 4. MAPPED TYPES FOR DIAGNOSTICS ===
// TODO: Create a DiagnosticForm<T> type that turns every field into a form field
// e.g. { name: string } -> { name: { value: string; isValid: boolean; error?: string } }

// === 5. SIMPLE TESTING SYSTEM (TDD simulation) ===
// TODO: Create test functions that verify the system is correct
function assertEqual<T>(actual: T, expected: T, testName: string): void {
  const passed = JSON.stringify(actual) === JSON.stringify(expected);
  console.log(passed ? `PASS: ${testName}` : `FAIL: ${testName}`);
  if (!passed) {
    console.log(`  Expected: ${JSON.stringify(expected)}`);
    console.log(`  Actual:   ${JSON.stringify(actual)}`);
  }
}

// TODO: Write tests for the diagnostic system
// Test 1: Registering a dinosaur
// Test 2: Diagnosing a carnivore vs a herbivore
// Test 3: Generating a report
// Test 4: Validating input data

console.log("Diagnostic system - run the tests!");

Docs entries used in this lesson

Spotted a mistake in this lesson?

  1. Project to submitMentor Project: Module 10
  2. VideoVideo: Module Summary

Useful articles