JavaScript and TypeScript course · Module 6: TypeScript Basics

Generic functions

13 min read ·
In this lesson11

Welcome back to the most advanced genetics laboratory in Jurassic Park! Dr. Henry Wu today invites us to explore one of the most powerful TypeScript mechanisms - generic functions. Just as advanced genetic engineering allows us to create new dinosaur species with different DNA, generic functions allow the creation of flexible, reusable solutions that work with different data types while maintaining full type safety.

What are generic functions?

Generic functions are functions that can work with different data types while maintaining full type control. Instead of defining a specific type for a parameter and return value, we use type parameters (usually denoted as T, U, K, etc.), which are "filled in" with specific types at the moment the function is called.

Imagine that instead of creating a separate function for each dinosaur species, you can create one generic function that will work with every species!

Basic syntax of generic functions

Let's look at how generic functions are defined and used in TypeScript:

// Simple generic function - returns the same element that was passed
function geneticIdentity<T>(obj: T): T {
  return obj;
}

// Use with different types
const dnaChain: string = geneticIdentity<string>("ACGTACGT");
const triceratopsAge: number = geneticIdentity<number>(12);
const activeStatus: boolean = geneticIdentity<boolean>(true);

// TypeScript can often infer the generic type from the passed argument
const aggressionLevel = geneticIdentity(7); // TypeScript infers T as number

In the above example:

  1. We define a generic function geneticIdentity with type parameter T
  2. The function takes an argument of type T and returns a value of the same type
  3. We use the function with different types: string, number, boolean
  4. In the last example TypeScript automatically infers the generic type from the passed argument

Generic functions with multiple type parameters

Generic functions can have multiple type parameters, allowing more complex operations:

// Generic function with two type parameters
function pairDinosaurData<T, U>(first: T, second: U): [T, U] {
  return [first, second];
}

// Sample usage
interface BasicDinosaurData {
  name: string;
  species: string;
  age: number;
}

interface HealthData {
  bodyTemperature: number;
  heartRate: number;
  energyLevel: number;
}

const rexBasic: BasicDinosaurData = {
  name: "Rex",
  species: "Tyrannosaurus",
  age: 7
};

const rexHealth: HealthData = {
  bodyTemperature: 38.2,
  heartRate: 76,
  energyLevel: 8.5
};

// Combining different types of data
const fullRexData = pairDinosaurData<BasicDinosaurData, HealthData>(
  rexBasic,
  rexHealth
);

console.log(`${fullRexData[0].name} has body temperature ${fullRexData[1].bodyTemperature}°C`);

Generic Constraints

Sometimes we want our generic functions to work only with specific data types that satisfy certain requirements. We can achieve this using generic constraints via the extends keyword:

// Defining an interface describing minimum requirements
interface BasicDinosaurInfo {
  id: string;
  name: string;
  species: string;
}

// Generic function with constraint - T must contain at least the properties from BasicDinosaurInfo
function displayDinosaurInfo<T extends BasicDinosaurInfo>(dino: T): void {
  console.log(`ID: ${dino.id}`);
  console.log(`Name: ${dino.name}`);
  console.log(`Species: ${dino.species}`);

  // We can also access additional properties that may be present in T
  console.log("Additional information:");
  const basicKeys = Object.keys({} as BasicDinosaurInfo);
  Object.entries(dino).forEach(([key, value]) => {
    if (!basicKeys.includes(key)) {
      console.log(`- ${key}: ${value}`);
    }
  });
}

// Example usage with different types satisfying the constraint
interface TRex extends BasicDinosaurInfo {
  biteForce: number;
  runSpeed: number;
}

const rex: TRex = {
  id: "TREX-001",
  name: "Rexy",
  species: "Tyrannosaurus Rex",
  biteForce: 12800,
  runSpeed: 32
};

interface Velociraptor extends BasicDinosaurInfo {
  intelligence: number;
  packHunting: boolean;
}

const raptor: Velociraptor = {
  id: "VELOC-001",
  name: "Blue",
  species: "Velociraptor",
  intelligence: 9,
  packHunting: true
};

// Both calls will work because both types extend BasicDinosaurInfo
displayDinosaurInfo(rex);
displayDinosaurInfo(raptor);

// This would not work because required properties are missing
// displayDinosaurInfo({ weight: 5000, age: 12 });

In the above example:

  1. We define the BasicDinosaurInfo interface with minimum requirements
  2. We create a generic function that only works with types extending this interface
  3. The function can safely use the properties required by the interface
  4. We can use the function with different dinosaur types as long as they meet the basic requirements

Constraints with keyof

The keyof keyword allows constraining a generic parameter to the keys of another type. This is extremely useful when creating functions that operate on object keys:

// Function retrieving a property value based on its key
function getDinosaurProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

// Sample dinosaur data
interface DinosaurData {
  id: string;
  name: string;
  species: string;
  age: number;
  weight: number;
  predator: boolean;
  traits: string[];
}

const triceratops: DinosaurData = {
  id: "TRIC-001",
  name: "Tricky",
  species: "Triceratops",
  age: 15,
  weight: 9000,
  predator: false,
  traits: ["horns", "head shield", "strong legs"]
};

// Using the function with different keys
const triceratopsName = getDinosaurProperty(triceratops, "name");
console.log(`Name: ${triceratopsName}`); // TypeScript knows this is a string

const triceratopsAge = getDinosaurProperty(triceratops, "age");
console.log(`Age: ${triceratopsAge} years`); // TypeScript knows this is a number

const traits = getDinosaurProperty(triceratops, "traits");
console.log(`Traits: ${traits.join(", ")}`); // TypeScript knows this is string[]

// This would not work because "nonExistentProperty" is not a key of DinosaurData
// getDinosaurProperty(triceratops, "nonExistentProperty");

Default type parameters

Just as functions can have default values for their parameters, generic functions can have default types for type parameters:

// Generic function with default type parameter
function createDinosaurReport<T = DinosaurData>(data: T, label: string = "Standard report"): { data: T, label: string, timestamp: Date } {
  return {
    data,
    label,
    timestamp: new Date()
  };
}

// Using with default type
const standardReport = createDinosaurReport(triceratops);
console.log(`Report: ${standardReport.label}`);
console.log(`Data for: ${standardReport.data.name}`);

// Using with a different type
interface ClimateData {
  temperature: number;
  humidity: number;
  pressure: number;
  location: string;
}

const enclosureClimateData: ClimateData = {
  temperature: 28.5,
  humidity: 72,
  pressure: 1013,
  location: "Triceratops Enclosure"
};

const climateReport = createDinosaurReport<ClimateData>(
  enclosureClimateData,
  "Climate report"
);

console.log(`Report: ${climateReport.label}`);
console.log(`Temperature: ${climateReport.data.temperature}°C`);

Generic array operations and collection operations

Generic functions are especially useful when working with arrays and data collections:

// Generic function for filtering an array
function filterCollection<T>(collection: T[], predicate: (element: T) => boolean): T[] {
  return collection.filter(predicate);
}

// Sample dinosaur data
interface DinosaurBriefInfo {
  id: string;
  name: string;
  species: string;
  predator: boolean;
  weight: number;
}

const dinosaurs: DinosaurBriefInfo[] = [
  { id: "TREX-001", name: "Rex", species: "Tyrannosaurus", predator: true, weight: 8000 },
  { id: "VEL-001", name: "Blue", species: "Velociraptor", predator: true, weight: 150 },
  { id: "TRIC-001", name: "Tricky", species: "Triceratops", predator: false, weight: 9000 },
  { id: "STEG-001", name: "Spike", species: "Stegosaurus", predator: false, weight: 5000 },
  { id: "BRACH-001", name: "Brachie", species: "Brachiosaurus", predator: false, weight: 40000 }
];

// Filtering predatory dinosaurs
const predators = filterCollection<DinosaurBriefInfo>(
  dinosaurs,
  dino => dino.predator
);

console.log("Predators in the park:");
predators.forEach(dino => console.log(`- ${dino.name} (${dino.species})`));

// Filtering dinosaurs heavier than 10000 kg
const heavyDinosaurs = filterCollection<DinosaurBriefInfo>(
  dinosaurs,
  dino => dino.weight > 10000
);

console.log("\nHeavy dinosaurs:");
heavyDinosaurs.forEach(dino => console.log(`- ${dino.name}: ${dino.weight} kg`));

// More advanced generic function for mapping an array
function transformCollection<T, U>(collection: T[], transform: (element: T) => U): U[] {
  return collection.map(transform);
}

// Creating simpler objects from dinosaurs
const dinosaurLabels = transformCollection<DinosaurBriefInfo, { name: string, type: string }>(
  dinosaurs,
  dino => ({
    name: dino.name,
    type: dino.predator ? "predator" : "herbivore"
  })
);

console.log("\nDinosaur labels:");
dinosaurLabels.forEach(label => console.log(`- ${label.name}: ${label.type}`));

Generic classes and methods

Not only functions can be generic - classes and their methods can also use this powerful feature:

// Generic Collection class - can store data of any type
class Collection<T> {
  private items: T[] = [];

  // Method adding an element to the collection
  add(element: T): void {
    this.items.push(element);
  }

  // Method retrieving an element at a given index
  get(index: number): T | undefined {
    if (index >= 0 && index < this.items.length) {
      return this.items[index];
    }
    return undefined;
  }

  // Method returning all elements
  getAll(): T[] {
    return [...this.items];
  }

  // Method filtering elements
  filter(predicate: (element: T) => boolean): T[] {
    return this.items.filter(predicate);
  }

  // Generic method mapping to another type
  map<U>(transform: (element: T) => U): U[] {
    return this.items.map(transform);
  }

  // Method returning the number of elements
  itemsCount(): number {
    return this.items.length;
  }
}

// Example usage with dinosaurs
const dinosaurCollection = new Collection<DinosaurBriefInfo>();

// Adding dinosaurs to the collection
dinosaurs.forEach(dino => dinosaurCollection.add(dino));

// Getting a specific dinosaur
const first = dinosaurCollection.get(0);
if (first) {
  console.log(`First dinosaur: ${first.name} (${first.species})`);
}

// Filtering the collection
const smallDinosaurs = dinosaurCollection.filter(dino => dino.weight < 1000);
console.log(`Number of small dinosaurs: ${smallDinosaurs.length}`);

// Mapping to health reports
interface HealthReport {
  id: string;
  name: string;
  healthStatus: string;
  notes: string;
}

const healthReports = dinosaurCollection.map<HealthReport>(dino => ({
  id: dino.id,
  name: dino.name,
  healthStatus: "good",
  notes: dino.predator
    ? "Exercise special caution"
    : "Standard procedures"
}));

console.log("\nHealth reports:");
healthReports.forEach(report => {
  console.log(`- ${report.name}: ${report.healthStatus} (${report.notes})`);
});

Generic interfaces and types

Just like functions and classes, interfaces and types can also be generic:

// Generic interface for a storage system
interface System<T> {
  add(element: T): void;
  get(id: string): T | null;
  update(id: string, element: T): boolean;
  remove(id: string): boolean;
  getAll(): T[];
}

// Implementation of a generic storage system for dinosaurs
class DinosaurDatabase<T extends { id: string }> implements System<T> {
  private data: Map<string, T> = new Map();

  add(element: T): void {
    this.data.set(element.id, element);
  }

  get(id: string): T | null {
    return this.data.has(id) ? this.data.get(id)! : null;
  }

  update(id: string, element: T): boolean {
    if (this.data.has(id)) {
      this.data.set(id, element);
      return true;
    }
    return false;
  }

  remove(id: string): boolean {
    return this.data.delete(id);
  }

  getAll(): T[] {
    return Array.from(this.data.values());
  }
}

// Defining types using generic type
type DataWithAssignee<T> = {
  data: T;
  assignedEmployee: string;
  lastUpdate: Date;
};

// Using the generic type
type DinosaurWithKeeper = DataWithAssignee<DinosaurBriefInfo>;

// Creating a database for dinosaurs with assigned keepers
const keeperDatabase = new DinosaurDatabase<DinosaurWithKeeper>();

// Adding records
keeperDatabase.add({
  data: dinosaurs[0],
  assignedEmployee: "Owen Grady",
  lastUpdate: new Date(),
  id: dinosaurs[0].id
});

keeperDatabase.add({
  data: dinosaurs[1],
  assignedEmployee: "Dr. Henry Wu",
  lastUpdate: new Date(),
  id: dinosaurs[1].id
});

// Retrieving data
const rexWithKeeper = keeperDatabase.get("TREX-001");
if (rexWithKeeper) {
  console.log(`\nDinosaur ${rexWithKeeper.data.name} is under the care of ${rexWithKeeper.assignedEmployee}`);
  console.log(`Last updated: ${rexWithKeeper.lastUpdate.toLocaleDateString()}`);
}

Practical example: Park management system

Let's look at a comprehensive example of how generic functions can be used in the Jurassic Park management system:

// ===== JURASSIC PARK MANAGEMENT SYSTEM =====

// Base interfaces
interface ParkElement {
  id: string;
  name: string;
  elementType: string;
}

interface ParkArea extends ParkElement {
  elementType: "area";
  coordinates: [number, number];
  area: number; // in hectares
  securityLevel: 1 | 2 | 3 | 4 | 5;
}

interface DinosaurEnclosure extends ParkArea {
  elementType: "enclosure";
  residents: string[]; // Dinosaur IDs
  environmentType: "forest" | "savanna" | "swamp" | "coast" | "water";
  fenceStatus: "active" | "inactive" | "under repair";
}

interface ParkDinosaur extends ParkElement {
  elementType: "dinosaur";
  species: string;
  age: number;
  weight: number;
  predator: boolean;
  location: string; // Area ID
  healthStatus: "excellent" | "good" | "needs attention" | "sick" | "critical";
}

interface ParkEmployee extends ParkElement {
  elementType: "employee";
  position: string;
  accessLevel: 1 | 2 | 3 | 4 | 5;
  specialization: string[];
}

// Generic repository class
class Repository<T extends ParkElement> {
  private items: Map<string, T> = new Map();

  add(element: T): void {
    this.items.set(element.id, element);
  }

  get(id: string): T | undefined {
    return this.items.get(id);
  }

  getAll(): T[] {
    return Array.from(this.items.values());
  }

  update(id: string, data: Partial<T>): boolean {
    if (this.items.has(id)) {
      const element = this.items.get(id)!;
      this.items.set(id, { ...element, ...data });
      return true;
    }
    return false;
  }

  remove(id: string): boolean {
    return this.items.delete(id);
  }

  filter(predicate: (element: T) => boolean): T[] {
    return this.getAll().filter(predicate);
  }
}

// Generic function for finding relationships between elements
function findAssociations<T extends ParkElement, U extends ParkElement>(
  sources: T[],
  targets: U[],
  predicate: (source: T, target: U) => boolean
): Array<[T, U[]]> {
  return sources.map(source => {
    const relatedTargets = targets.filter(target => predicate(source, target));
    return [source, relatedTargets] as [T, U[]];
  });
}

// Generic function for generating reports
function generateReport<T extends ParkElement>(
  name: string,
  items: T[],
  formatElement: (element: T) => string
): string {
  let report = `=== ${name} ===\n`;
  report += `Generated on: ${new Date().toLocaleString()}\n`;
  report += `Number of elements: ${items.length}\n\n`;

  if (items.length === 0) {
    report += "No data to display.\n";
  } else {
    items.forEach(element => {
      report += formatElement(element) + "\n";
    });
  }

  return report;
}

// Simulating park data
// Creating repositories
const repoDinosaurs = new Repository<ParkDinosaur>();
const areasRepo = new Repository<ParkArea>();
const enclosuresRepo = new Repository<DinosaurEnclosure>();
const employeesRepo = new Repository<ParkEmployee>();

// Adding data to repositories
// Areas
const centralArea: ParkArea = {
  id: "AREA-001",
  name: "Central Area",
  elementType: "area",
  coordinates: [20.123, -75.456],
  area: 25,
  securityLevel: 1
};
areasRepo.add(centralArea);

// Enclosures
const tRexEnclosure: DinosaurEnclosure = {
  id: "ENC-001",
  name: "T-Rex Enclosure",
  elementType: "enclosure",
  coordinates: [20.145, -75.460],
  area: 8,
  securityLevel: 5,
  residents: ["DINO-001"],
  environmentType: "forest",
  fenceStatus: "active"
};
enclosuresRepo.add(tRexEnclosure);

const raptorEnclosure: DinosaurEnclosure = {
  id: "ENC-002",
  name: "Raptor Enclosure",
  elementType: "enclosure",
  coordinates: [20.150, -75.465],
  area: 5,
  securityLevel: 5,
  residents: ["DINO-002", "DINO-003", "DINO-004", "DINO-005"],
  environmentType: "savanna",
  fenceStatus: "active"
};
enclosuresRepo.add(raptorEnclosure);

// Dinosaurs
const trex: ParkDinosaur = {
  id: "DINO-001",
  name: "Rexy",
  elementType: "dinosaur",
  species: "Tyrannosaurus Rex",
  age: 7,
  weight: 8000,
  predator: true,
  location: "ENC-001",
  healthStatus: "good"
};
repoDinosaurs.add(trex);

const raptor1: ParkDinosaur = {
  id: "DINO-002",
  name: "Blue",
  elementType: "dinosaur",
  species: "Velociraptor",
  age: 4,
  weight: 150,
  predator: true,
  location: "ENC-002",
  healthStatus: "excellent"
};
repoDinosaurs.add(raptor1);

// Employees
const trainer: ParkEmployee = {
  id: "EMP-001",
  name: "Owen Grady",
  elementType: "employee",
  position: "Raptor Trainer",
  accessLevel: 4,
  specialization: ["Behaviorism", "Dinosaur training", "Field operations"]
};
employeesRepo.add(trainer);

const scientist: ParkEmployee = {
  id: "EMP-002",
  name: "Dr. Henry Wu",
  elementType: "employee",
  position: "Chief Geneticist",
  accessLevel: 5,
  specialization: ["Genetics", "Genetic engineering", "Cloning"]
};
employeesRepo.add(scientist);

// Sample use of generic functions

// 1. Finding dinosaurs in specific enclosures
const dinosaursInEnclosures = findAssociations<DinosaurEnclosure, ParkDinosaur>(
  enclosuresRepo.getAll(),
  repoDinosaurs.getAll(),
  (enclosure, dino) => enclosure.residents.includes(dino.id)
);

// 2. Generating enclosure status report
const enclosuresReport = generateReport<DinosaurEnclosure>(
  "ENCLOSURE STATUS REPORT",
  enclosuresRepo.getAll(),
  enclosure => {
    const residentsCount = enclosure.residents.length;
    return `${enclosure.name} (ID: ${enclosure.id})
    - Environment type: ${enclosure.environmentType}
    - Area: ${enclosure.area} ha
    - Fence status: ${enclosure.fenceStatus}
    - Security level: ${enclosure.securityLevel}
    - Number of inhabitants: ${residentsCount}`;
  }
);

// 3. Generating dinosaur health report
const dinosaurHealthReport = generateReport<ParkDinosaur>(
  "DINOSAUR HEALTH REPORT",
  repoDinosaurs.getAll(),
  dino => {
    const location = enclosuresRepo.get(dino.location)?.name || "Unknown";
    return `${dino.name} (${dino.species})
    - ID: ${dino.id}
    - Age: ${dino.age} years
    - Weight: ${dino.weight} kg
    - Health status: ${dino.healthStatus}
    - Location: ${location}`;
  }
);

// Displaying reports
console.log("=== DINOSAURS IN ENCLOSURES ===");
dinosaursInEnclosures.forEach(([enclosure, dinosaurs]) => {
  console.log(`Enclosure: ${enclosure.name}`);
  if (dinosaurs.length === 0) {
    console.log("  No inhabitants");
  } else {
    dinosaurs.forEach(dino => {
      console.log(`  - ${dino.name} (${dino.species}): ${dino.healthStatus}`);
    });
  }
});

console.log("\n" + enclosuresReport);
console.log("\n" + dinosaurHealthReport);

Summary

Generic functions are an extremely powerful tool in TypeScript that allows the creation of flexible, reusable components while maintaining full type safety. Like Dr. Wu's advanced genetic techniques, generic functions allow the creation of highly adaptive solutions that can work with different data types.

TechniqueUse in Jurassic Park
Basic generic functionsHandling different types of dinosaur data
Multi-parameter generic functionsCombining dinosaur data from different sources
Generic constraintsEnsuring functions only work with appropriate dinosaur types
keyof constraintsSafe access to dinosaur properties
Default type parametersSimplifying work with the most commonly used data types
Generic collection operationsEfficiently managing groups of dinosaurs
Generic classes and methodsCreating flexible specimen management systems
Generic interfaces and typesDefining consistent contracts for different park subsystems

Dr. Wu summarizes: "Just as our breakthrough genetic techniques allowed us to bring back to life species that disappeared from the Earth 65 million years ago, TypeScript generic functions allow programmers to create flexible, adaptive solutions that can evolve with the needs of the system. Remember however, that with great power comes great responsibility - both in genetic engineering and in programming."

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

// ===========================================
// 1. Basic generic functions
// ===========================================
console.log("=== BASIC GENERICS ===");

// A simple generic function
function identity<T>(value: T): T {
  return value;
}

const stringValue = identity<string>("Tyrannosaurus Rex");
const numberValue = identity<number>(8000);
const boolValue = identity<boolean>(true);

console.log("String:", stringValue);
console.log("Number:", numberValue);
console.log("Boolean:", boolValue);

// Type inference - TypeScript will infer the type
const autoString = identity("Auto string"); // T = string
const autoNumber = identity(42); // T = number

console.log("Auto string:", autoString);
console.log("Auto number:", autoNumber);

// ===========================================
// 2. Generics with arrays
// ===========================================
console.log("\n=== GENERICS WITH ARRAYS ===");

function getFirst<T>(array: T[]): T | undefined {
  return array[0];
}

const dinosaurs = ["T-Rex", "Velociraptor", "Triceratops"];
const weights = [8000, 350, 5000];

console.log("First dinosaur:", getFirst(dinosaurs));
console.log("First weight:", getFirst(weights));

function getLast<T>(array: T[]): T | undefined {
  return array[array.length - 1];
}

console.log("Last dinosaur:", getLast(dinosaurs));

// ===========================================
// 3. Generics with multiple types
// ===========================================
console.log("\n=== MULTIPLE GENERIC TYPES ===");

function createPair<K, V>(key: K, value: V): { key: K; value: V } {
  return { key, value };
}

const pair1 = createPair<string, number>("age", 5);
const pair2 = createPair<number, string>(1, "Rexy");
const pair3 = createPair("weight", 8000); // type inference

console.log("Pair 1:", pair1);
console.log("Pair 2:", pair2);
console.log("Pair 3:", pair3);

// ===========================================
// 4. Generic constraints
// ===========================================
console.log("\n=== GENERIC CONSTRAINTS ===");

interface HasName {
  name: string;
}

// T must have property 'name'
function logName<T extends HasName>(entity: T): T {
  console.log(`Name: ${entity.name}`);
  return entity;
}

interface Dinosaur {
  name: string;
  species: string;
}

const trex: Dinosaur = {
  name: "Rexy",
  species: "Tyrannosaurus Rex"
};

logName(trex);
// logName({ age: 5 }); // Error: no 'name' property

// Constraint with extends
function getLength<T extends { length: number }>(value: T): number {
  return value.length;
}

console.log("String length:", getLength("Hello"));
console.log("Array length:", getLength([1, 2, 3]));
// console.log(getLength(123)); // Error: no 'length' property

// ===========================================
// 5. Generics with interfaces
// ===========================================
console.log("\n=== GENERICS WITH INTERFACES ===");

interface Container<T> {
  value: T;
  getValue(): T;
  setValue(value: T): void;
}

class DinosaurContainer implements Container<Dinosaur> {
  value: Dinosaur;

  constructor(value: Dinosaur) {
    this.value = value;
  }

  getValue(): Dinosaur {
    return this.value;
  }

  setValue(value: Dinosaur): void {
    this.value = value;
  }
}

const dinoContainer = new DinosaurContainer(trex);
console.log("Container value:", dinoContainer.getValue());

// ===========================================
// 6. Generic Repository Pattern
// ===========================================
console.log("\n=== REPOSITORY PATTERN ===");

interface Repository<T> {
  items: T[];
  add(item: T): void;
  remove(item: T): void;
  find(predicate: (item: T) => boolean): T | undefined;
  getAll(): T[];
}

class DinosaurRepository implements Repository<Dinosaur> {
  items: Dinosaur[] = [];

  add(dinosaur: Dinosaur): void {
    this.items.push(dinosaur);
    console.log(`Added ${dinosaur.name} to repository`);
  }

  remove(dinosaur: Dinosaur): void {
    const index = this.items.findIndex(d => d.name === dinosaur.name);
    if (index !== -1) {
      this.items.splice(index, 1);
      console.log(`Removed ${dinosaur.name} from repository`);
    }
  }

  find(predicate: (dinosaur: Dinosaur) => boolean): Dinosaur | undefined {
    return this.items.find(predicate);
  }

  getAll(): Dinosaur[] {
    return [...this.items];
  }
}

const dinoRepo = new DinosaurRepository();
dinoRepo.add(trex);
dinoRepo.add({ name: "Blue", species: "Velociraptor" });

const foundDino = dinoRepo.find(d => d.name === "Blue");
console.log("Found:", foundDino);

console.log("All dinosaurs:", dinoRepo.getAll().map(d => d.name));

// ===========================================
// 7. Generic Array functions
// ===========================================
console.log("\n=== GENERIC ARRAY FUNCTIONS ===");

function map<T, U>(array: T[], fn: (item: T) => U): U[] {
  const result: U[] = [];
  for (const item of array) {
    result.push(fn(item));
  }
  return result;
}

const dinoNames = ["Rexy", "Blue", "Charlie"];
const upperNames = map(dinoNames, name => name.toUpperCase());
const nameLengths = map(dinoNames, name => name.length);

console.log("Upper names:", upperNames);
console.log("Name lengths:", nameLengths);

function filter<T>(array: T[], predicate: (item: T) => boolean): T[] {
  const result: T[] = [];
  for (const item of array) {
    if (predicate(item)) {
      result.push(item);
    }
  }
  return result;
}

const longNames = filter(dinoNames, name => name.length > 4);
console.log("Long names:", longNames);

// ===========================================
// 8. Generic Promise
// ===========================================
console.log("\n=== GENERIC PROMISE ===");

function fetchDinosaur(id: number): Promise<Dinosaur> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        name: `Dinosaur-${id}`,
        species: "Unknown"
      });
    }, 100);
  });
}

async function getDinosaurData(): Promise<void> {
  const dino = await fetchDinosaur(1);
  console.log("Fetched dinosaur:", dino);
}

getDinosaurData();

// ===========================================
// 9. Generic Default Types
// ===========================================
console.log("\n=== DEFAULT TYPES ===");

interface Response<T = any> {
  status: number;
  data: T;
  message: string;
}

const stringResponse: Response<string> = {
  status: 200,
  data: "Success",
  message: "OK"
};

const dinoResponse: Response<Dinosaur> = {
  status: 200,
  data: trex,
  message: "Dinosaur found"
};

const defaultResponse: Response = {
  status: 404,
  data: null,
  message: "Not found"
};

console.log("String response:", stringResponse);
console.log("Dino response:", dinoResponse.data.name);

// ===========================================
// 10. Keyof operator with Generics
// ===========================================
console.log("\n=== KEYOF OPERATOR ===");

function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

const blue: Dinosaur = {
  name: "Blue",
  species: "Velociraptor"
};

const dinoName = getProperty(blue, "name"); // string
const dinoSpecies = getProperty(blue, "species"); // string
// const invalid = getProperty(blue, "age"); // Error

console.log("Property 'name':", dinoName);
console.log("Property 'species':", dinoSpecies);

// ===========================================
// 11. Generic Utility Functions
// ===========================================
console.log("\n=== UTILITY FUNCTIONS ===");

function merge<T, U>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

const basicInfo = { name: "Rexy", age: 5 };
const detailedInfo = { species: "T-Rex", weight: 8000 };

const fullInfo = merge(basicInfo, detailedInfo);
console.log("Merged:", fullInfo);

function partial<T>(obj: T): Partial<T> {
  return { ...obj };
}

const partialDino = partial(trex);
console.log("Partial:", partialDino);

// ===========================================
// 12. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Generic functions - <T>");
console.log("Multiple types - <K, V>");
console.log("Constraints - <T extends Type>");
console.log("Generic interfaces - Interface<T>");
console.log("Repository pattern - a universal repository");
console.log("Generic Promise - asynchronous types");
console.log("Keyof operator - access to keys");
console.log("Utility functions - universal tools");

console.log("\nGeneric functions 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. What is a generic function in TypeScript?

  2. 2. How do you constrain a generic parameter T to only accept types with an 'id' property?

Hands-on tasks in the game

  • Code editor

    Implement a generic findById<T> function that takes an array of objects with an id field and returns an element or undefined.

  • Code editor

    Implement a generic filterByProperty<T, K> function that takes an array, key, and value, returning filtered elements.

  • Click in order

    Arrange the elements of a generic TypeScript function:

  • Vertical ordering

    Order generic concepts from simplest to most advanced:

  1. QuestionWhat Are Generic Functions
  2. QuestionGeneric Constraints
  3. Coding taskPractice: Generic Function
  4. Coding taskPractice: Generic Search Function
  5. Click in orderSorting: Generic Function
  6. Put in orderFrom Simple to Advanced Generics

Useful articles