JavaScript and TypeScript course ยท Module 6: TypeScript Basics

Function Overloading

13 min read ยท
In this lesson9

"In Jurassic Park, precision is key," says Dr. Henry Wu, looking at his highly specialized laboratory equipment. "The same DNA analyzer can examine samples in different formats - from dinosaur blood, through fossils, to amber. Similarly in TypeScript, one function can handle different sets of parameters and return different types of data."

Welcome to the world of function overloading - a powerful TypeScript mechanism that allows defining functions that accept different kinds of parameters and return different result types.

What is function overloading?

Function overloading is a mechanism that enables defining multiple signatures for a single function. This way we can create a function that behaves differently depending on the number, types, and structure of the passed parameters.

In other words, just as scientists in Jurassic Park can use the same equipment for different procedures, we can use one function for different operations, while maintaining full type safety.

Basics of function overloading

In TypeScript, function overloading consists of two parts:

  1. Overload signatures - definitions of parameter types and return values
  2. Implementation signature - the actual function implementation, which must be compatible with all overload signatures

Let's look at a simple example:

// Overload signatures
function analyzeSample(id: number): string;
function analyzeSample(name: string): string;

// Implementation signature
function analyzeSample(argument: number | string): string {
  if (typeof argument === "number") {
    return `Analyzing sample with ID: ${argument}`;
  } else {
    return `Analyzing sample: ${argument}`;
  }
}

// Using the function
const result1 = analyzeSample(42);         // TypeScript knows the argument is number
const result2 = analyzeSample("Raptor-01"); // TypeScript knows the argument is string
// const error = analyzeSample(true);      // Error, boolean is not an accepted type

In the above example:

  1. We defined two overload signatures - one accepting number, another accepting string
  2. We created one implementation that handles both types
  3. TypeScript ensures the function is only called with arguments of the correct types

Overloading with different return types

The true power of overloading is revealed when a function can return different types depending on the input parameters:

// Overload signatures with different return types
function getDinosaurData(id: number): { id: number; species: string; age: number };
function getDinosaurData(name: string): { name: string; species: string };

// Implementation signature
function getDinosaurData(identifier: number | string): any {
  if (typeof identifier === "number") {
    // Fetching full data based on ID
    return {
      id: identifier,
      species: "Tyrannosaurus",
      age: 7
    };
  } else {
    // Fetching basic information based on name
    return {
      name: identifier,
      species: "Velociraptor"
    };
  }
}

// Usage with full type information
const dinosaurById = getDinosaurData(42);
console.log(dinosaurById.age);  // OK, TypeScript knows that property 'age' exists

const dinosaurByName = getDinosaurData("Blue");
// console.log(dinosaurByName.age);  // Error, TypeScript knows the object has no 'age' property
console.log(dinosaurByName.species);  // OK

Note that despite using any in the implementation signature, TypeScript provides full type safety when using the function, based on the overload signatures.

Overloading with different numbers of parameters

We can also overload functions that accept different numbers of parameters:

// Overloading with different number of parameters
function monitorDinosaur(id: number): string;
function monitorDinosaur(id: number, detailLevel: "basic" | "full"): Object;
function monitorDinosaur(id: number, detailLevel?: "basic" | "full"): string | Object {
  if (!detailLevel) {
    return `Monitoring dinosaur with ID ${id}...`;
  } else if (detailLevel === "basic") {
    return {
      status: "active",
      location: "Sector B"
    };
  } else {
    return {
      status: "active",
      location: "Sector B",
      speed: "2 km/h",
      heartRate: 80,
      bodyTemperature: 38,
      lastMeal: "2 hours ago",
      aggressionLevel: "low"
    };
  }
}

// Usage
const message = monitorDinosaur(5);  // Returns string
const basicData = monitorDinosaur(5, "basic");  // Returns simple object
const detailedData = monitorDinosaur(5, "full");  // Returns extended object

Method overloading in classes

Function overloading can also be applied to methods in classes:

class ResearchTeam {
  // Overload signatures for sendTeam method
  sendTeam(target: { x: number, y: number }): string;
  sendTeam(sector: string): string;
  sendTeam(target: string, size: number): string;

  // Method implementation
  sendTeam(target: { x: number, y: number } | string, size?: number): string {
    if (typeof target === "object") {
      return `Sending team to coordinates: ${target.x}, ${target.y}`;
    } else if (size !== undefined) {
      return `Sending a ${size}-person team to sector: ${target}`;
    } else {
      return `Sending standard team to sector: ${target}`;
    }
  }
}

const team = new ResearchTeam();
console.log(team.sendTeam({ x: 123, y: 456 }));  // Using coordinates
console.log(team.sendTeam("B-5"));  // Using sector name
console.log(team.sendTeam("C-7", 5));  // Using sector name and team size

Advanced function overloading examples

Different types for different parameter combinations

// Overload signatures for complex analysis
function analyzeBehavior(
  speciesId: number,
  behavioralData: number[]
): { aggressionLevel: number; risk: string };

function analyzeBehavior(
  speciesId: number,
  behavioralData: number[],
  historicalData: boolean
): { aggressionLevel: number; risk: string; comparison: string };

// Implementation
function analyzeBehavior(
  speciesId: number,
  behavioralData: number[],
  historicalData?: boolean
): any {
  // Basic analysis
  const averageActivity = behavioralData.reduce((a, b) => a + b, 0) / behavioralData.length;
  const aggressionLevel = Math.round(averageActivity * 10) / 10;

  let risk = "low";
  if (aggressionLevel > 7) risk = "high";
  else if (aggressionLevel > 4) risk = "medium";

  // Basic result
  const result = { aggressionLevel, risk };

  // Extended result if historical data requested
  if (historicalData) {
    // Simulating retrieval of historical data
    const historicalLevel = 3.5;
    const change = aggressionLevel - historicalLevel;
    const comparison = change > 0
      ? `Increase by ${change.toFixed(1)} pts`
      : `Decrease by ${Math.abs(change).toFixed(1)} pts`;

    return { ...result, comparison };
  }

  return result;
}

// Usage
const basicAnalysis = analyzeBehavior(1, [2, 4, 3, 6, 1]);
console.log(basicAnalysis.risk);  // "medium"

const extendedAnalysis = analyzeBehavior(1, [2, 4, 3, 6, 1], true);
console.log(extendedAnalysis.comparison);  // "Increase by 0.8 pts"

Generic function overloads

Function overloads can be even more powerful when combined with generic types:

// Generic function overloads
function getData<T extends { id: number }>(id: number): T;
function getData<T extends { name: string }>(name: string): T;
function getData<T>(identifier: number | string): T {
  // Implementation communicating with the database and returning the appropriate type
  if (typeof identifier === "number") {
    // Simulating different data types for different IDs
    if (identifier < 100) {
      // Dinosaur
      return {
        id: identifier,
        species: "Tyrannosaurus",
        age: 7,
        weight: 7500
      } as unknown as T;
    } else {
      // Employee
      return {
        id: identifier,
        firstName: "Owen",
        lastName: "Grady",
        position: "Trainer"
      } as unknown as T;
    }
  } else {
    // Search by name
    if (identifier.includes("REX")) {
      return {
        name: identifier,
        species: "Tyrannosaurus",
        population: 1
      } as unknown as T;
    } else {
      return {
        name: identifier,
        type: "Sector",
        capacity: 12
      } as unknown as T;
    }
  }
}

// Interfaces for typing
interface Dinosaur {
  id: number;
  species: string;
  age: number;
  weight: number;
}

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  position: string;
}

interface SpeciesInfo {
  name: string;
  species: string;
  population: number;
}

// Usage with explicit generic type
const trex = getData<Dinosaur>(1);
console.log(trex.age);  // OK, TypeScript knows this is a Dinosaur

const employee = getData<Employee>(101);
console.log(employee.position);  // OK, TypeScript knows this is a Employee

const species = getData<SpeciesInfo>("T-REX-01");
console.log(species.population);  // OK, TypeScript knows this is a SpeciesInfo

Best practices and pitfalls

1. The implementation signature must be compatible with all overload signatures

Parameters in the implementation signature must be defined so they can handle all possible combinations from the overload signatures:

// GOOD:
function test(a: string): number;
function test(a: number, b: boolean): string;
function test(a: string | number, b?: boolean): number | string {
  // Implementation
  return 0 as any;
}

// BAD:
function bad(a: string): number;
function bad(a: number, b: boolean): string;
// Error: parameter 'b' in the implementation must be optional
function bad(a: string | number, b: boolean): number | string {
  return 0 as any;
}

2. Overload signatures are checked in order

TypeScript checks overload signatures from top to bottom, so more specific signatures should be defined before more general ones:

// BAD - more general signature shadows more specific one
function wrongOrder(data: any[]): number;
function wrongOrder(data: number[]): string;  // This signature will never be matched
function wrongOrder(data: any[]): number | string {
  if (Array.isArray(data) && data.every(d => typeof d === "number")) {
    return "Array of numbers";
  } else {
    return data.length;
  }
}

// GOOD - more specific signature comes first
function correctOrder(data: number[]): string;
function correctOrder(data: any[]): number;
function correctOrder(data: any[]): number | string {
  if (Array.isArray(data) && data.every(d => typeof d === "number")) {
    return "Array of numbers";
  } else {
    return data.length;
  }
}

3. Balancing between overloading, optional parameters, and union types

Sometimes optional parameters or union types may be a better solution than extensive overloads:

// Instead of many overloads:
function option1(id: number): void;
function option1(id: number, mode: string): void;
function option1(id: number, mode: string, extra: boolean): void;
// ...and many more versions

// Better to use optional parameters:
function option2(id: number, mode?: string, extra?: boolean): void {
  // Implementation
}

Practical example: Jurassic Park management system

Let's look at a comprehensive example of how function overloading can be used in a Jurassic Park management system:

// Defining types used in the system
type DinosaurStatus = "healthy" | "sick" | "in treatment" | "in a coma";
type DinosaurSpecies = "Tyrannosaurus" | "Velociraptor" | "Triceratops" | "Brachiosaurus";
type ThreatLevelType = 1 | 2 | 3 | 4 | 5;

interface BasicData {
  id: number;
  name: string;
  species: DinosaurSpecies;
  status: DinosaurStatus;
  threatLevel: ThreatLevelType;
}

interface HealthData {
  bodyTemperature: number;
  heartRate: number;
  stressFactor: number;
  lastMeal: Date;
  weightKg: number;
}

interface LocationData {
  sector: string;
  gpsCoordinates: [number, number];
  lastUpdate: Date;
}

interface SecurityReport {
  fenceStatus: "operational" | "damaged" | "under repair";
  powerActive: boolean;
  peopleInSector: number;
  activeAlerts: string[];
}

// Class for managing dinosaurs with overloaded methods
class DinosaurManagementSystem {
  private database: Map<number, {
    basic: BasicData;
    health?: HealthData;
    location?: LocationData;
    security?: SecurityReport;
  }> = new Map();

  // Method for adding a dinosaur to the system
  addDinosaur(data: BasicData): number;
  addDinosaur(data: BasicData, health: HealthData): number;
  addDinosaur(data: BasicData, health: HealthData, location: LocationData): number;
  addDinosaur(
    data: BasicData,
    health?: HealthData,
    location?: LocationData
  ): number {
    const newRecord = {
      basic: data,
      health,
      location: location
    };

    this.database.set(data.id, newRecord);
    console.log(`Added dinosaur: ${data.name} (ID: ${data.id})`);
    return data.id;
  }

  // Overloaded method for retrieving dinosaur data
  getData(id: number): BasicData;
  getData(id: number, type: "health"): HealthData | undefined;
  getData(id: number, type: "location"): LocationData | undefined;
  getData(id: number, type: "security"): SecurityReport | undefined;
  getData(id: number, type: "all"): {
    basic: BasicData;
    health?: HealthData;
    location?: LocationData;
    security?: SecurityReport;
  };
  getData(id: number, type?: "health" | "location" | "security" | "all"): any {
    const record = this.database.get(id);

    if (!record) {
      throw new Error(`Dinosaur with ID ${id} does not exist in the system.`);
    }

    if (!type) {
      return record.basic;
    }

    switch (type) {
      case "health":
        return record.health;
      case "location":
        return record.location;
      case "security":
        return record.security;
      case "all":
        return record;
    }
  }

  // Overloaded method for updating data
  updateData(id: number, data: Partial<BasicData>): boolean;
  updateData(id: number, data: HealthData, type: "health"): boolean;
  updateData(id: number, data: LocationData, type: "location"): boolean;
  updateData(id: number, data: SecurityReport, type: "security"): boolean;
  updateData(
    id: number,
    data: Partial<BasicData> | HealthData | LocationData | SecurityReport,
    type?: "health" | "location" | "security"
  ): boolean {
    const record = this.database.get(id);

    if (!record) {
      console.error(`Dinosaur with ID ${id} does not exist in the system.`);
      return false;
    }

    if (!type) {
      // Updating basic data
      record.basic = { ...record.basic, ...data as Partial<BasicData> };
      console.log(`Updated basic data for dinosaur ID: ${id}`);
    } else {
      switch (type) {
        case "health":
          record.health = { ...(record.health || {}), ...data as HealthData };
          console.log(`Updated health data for dinosaur ID: ${id}`);
          break;
        case "location":
          record.location = { ...(record.location || {}), ...data as LocationData };
          console.log(`Updated location data for dinosaur ID: ${id}`);
          break;
        case "security":
          record.security = { ...(record.security || {}), ...data as SecurityReport };
          console.log(`Updated security data for dinosaur ID: ${id}`);
          break;
      }
    }

    this.database.set(id, record);
    return true;
  }

  // Overloaded method for generating reports
  generateReport(): string; // Report for all dinosaurs
  generateReport(species: DinosaurSpecies): string; // Report for selected species
  generateReport(threatLevel: ThreatLevelType): string; // Report for threat level
  generateReport(filter?: DinosaurSpecies | ThreatLevelType): string {
    let dinosaurs = Array.from(this.database.values()).map(d => d.basic);

    if (filter) {
      if (typeof filter === "string") {
        // Filtering by species
        dinosaurs = dinosaurs.filter(d => d.species === filter);
        return this.formatReport(`Report for species: ${filter}`, dinosaurs);
      } else {
        // Filtering by threat level
        dinosaurs = dinosaurs.filter(d => d.threatLevel === filter);
        return this.formatReport(`Report for threat level: ${filter}`, dinosaurs);
      }
    }

    return this.formatReport("Full report of all dinosaurs", dinosaurs);
  }

  private formatReport(title: string, dinosaurs: BasicData[]): string {
    let report = `=== ${title} ===\n`;
    report += `Date: ${new Date().toLocaleString()}\n`;
    report += `Number of dinosaurs: ${dinosaurs.length}\n\n`;

    dinosaurs.forEach(d => {
      report += `ID: ${d.id} | ${d.name} | ${d.species} | Status: ${d.status} | Threat: ${d.threatLevel}\n`;
    });

    return report;
  }
}

// Example usage of the system
const system = new DinosaurManagementSystem();

// Adding dinosaurs with different data sets
const rexId = system.addDinosaur({
  id: 1,
  name: "Rexy",
  species: "Tyrannosaurus",
  status: "healthy",
  threatLevel: 5
});

const raptorId = system.addDinosaur(
  {
    id: 2,
    name: "Blue",
    species: "Velociraptor",
    status: "healthy",
    threatLevel: 4
  },
  {
    bodyTemperature: 38.5,
    heartRate: 85,
    stressFactor: 2.1,
    lastMeal: new Date(Date.now() - 3600000), // 1 hour ago
    weightKg: 160
  }
);

const triceratopsId = system.addDinosaur(
  {
    id: 3,
    name: "Tricy",
    species: "Triceratops",
    status: "healthy",
    threatLevel: 2
  },
  {
    bodyTemperature: 37.2,
    heartRate: 45,
    stressFactor: 1.3,
    lastMeal: new Date(Date.now() - 7200000), // 2 hours ago
    weightKg: 8500
  },
  {
    sector: "B-7",
    gpsCoordinates: [34.5678, -118.2345],
    lastUpdate: new Date()
  }
);

// Retrieving different types of data
const rexBasic = system.getData(rexId);
console.log(`Dinosaur ${rexBasic.name} has threat level ${rexBasic.threatLevel}`);

const raptorHealth = system.getData(raptorId, "health");
if (raptorHealth) {
  console.log(`Body temperature of raptor: ${raptorHealth.bodyTemperature}ยฐC`);
}

const triceratopsLocation = system.getData(triceratopsId, "location");
if (triceratopsLocation) {
  console.log(`Triceratops is located in sector: ${triceratopsLocation.sector}`);
}

// Updating data
system.updateData(rexId, { status: "in treatment" });

system.updateData(raptorId,
  {
    bodyTemperature: 39.2,
    heartRate: 95,
    stressFactor: 4.5,
    lastMeal: new Date(),
    weightKg: 162
  },
  "health"
);

// Generating reports
console.log(system.generateReport());
console.log(system.generateReport("Velociraptor"));
console.log(system.generateReport(5));

Summary

Function overloading is a powerful TypeScript mechanism that allows creating flexible APIs while maintaining full type safety. Just as scientists in Jurassic Park must adapt their procedures to different dinosaur species, programmers can create functions that adapt to different sets of parameters.

The most important rules of function overloading:

  1. Define overload signatures before the implementation signature
  2. The implementation signature must be compatible with all overload signatures
  3. Place more specific signatures before more general ones
  4. Use overloads when you want different return types for different input parameters
  5. Consider alternatives (optional parameters, union types) for simpler cases

"In programming, just as in dinosaur genetics," says Dr. Wu with a smile, "the true power lies in the ability to adapt. Function overloading is like creating adaptive DNA sequences - the same function can evolve to serve different purposes, while maintaining its integrity and safety."

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

// ===========================================
// 1. Basic overloading
// ===========================================
console.log("=== BASIC OVERLOADING ===");

// Overload definitions
function identify(value: string): string;
function identify(value: number): number;
function identify(value: boolean): boolean;

// Implementation
function identify(value: string | number | boolean): string | number | boolean {
  return value;
}

console.log("String:", identify("T-Rex"));
console.log("Number:", identify(8000));
console.log("Boolean:", identify(true));

// ===========================================
// 2. Overloading with different parameters
// ===========================================
console.log("\n=== DIFFERENT PARAMETERS ===");

// Overloads
function createDinosaur(name: string): string;
function createDinosaur(name: string, species: string): string;
function createDinosaur(name: string, species: string, age: number): string;

// Implementation
function createDinosaur(
  name: string,
  species?: string,
  age?: number
): string {
  let result = `Dinosaur: ${name}`;
  if (species) result += `, Species: ${species}`;
  if (age !== undefined) result += `, Age: ${age}`;
  return result;
}

console.log(createDinosaur("Rexy"));
console.log(createDinosaur("Blue", "Velociraptor"));
console.log(createDinosaur("Charlie", "Velociraptor", 3));

// ===========================================
// 3. Overloading with different returns
// ===========================================
console.log("\n=== DIFFERENT RETURN TYPES ===");

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

// Overloads with different return types
function findDinosaur(id: number): Dinosaur | undefined;
function findDinosaur(name: string): Dinosaur[];

// Implementation
function findDinosaur(
  query: number | string
): Dinosaur | undefined | Dinosaur[] {
  const database: Dinosaur[] = [
    { name: "Rexy", species: "T-Rex", age: 5 },
    { name: "Blue", species: "Velociraptor", age: 3 },
    { name: "Charlie", species: "Velociraptor", age: 3 }
  ];

  if (typeof query === "number") {
    return database[query];
  } else {
    return database.filter(d => d.name.includes(query));
  }
}

console.log("Find by ID:", findDinosaur(0));
console.log("Find by name:", findDinosaur("Blue"));

// ===========================================
// 4. Overloading with objects
// ===========================================
console.log("\n=== OVERLOADING WITH OBJECTS ===");

interface SearchByName {
  type: "name";
  name: string;
}

interface SearchBySpecies {
  type: "species";
  species: string;
}

interface SearchByAge {
  type: "age";
  minAge: number;
  maxAge: number;
}

type SearchCriteria = SearchByName | SearchBySpecies | SearchByAge;

// Overloads
function search(criteria: SearchByName): Dinosaur[];
function search(criteria: SearchBySpecies): Dinosaur[];
function search(criteria: SearchByAge): Dinosaur[];

// Implementation
function search(criteria: SearchCriteria): Dinosaur[] {
  const database: Dinosaur[] = [
    { name: "Rexy", species: "T-Rex", age: 5 },
    { name: "Blue", species: "Velociraptor", age: 3 },
    { name: "Charlie", species: "Velociraptor", age: 3 },
    { name: "Delta", species: "Velociraptor", age: 4 }
  ];

  if (criteria.type === "name") {
    return database.filter(d => d.name === criteria.name);
  } else if (criteria.type === "species") {
    return database.filter(d => d.species === criteria.species);
  } else {
    return database.filter(
      d => d.age >= criteria.minAge && d.age <= criteria.maxAge
    );
  }
}

console.log("Search by name:", search({ type: "name", name: "Blue" }));
console.log("Search by species:", search({ type: "species", species: "Velociraptor" }));
console.log("Search by age:", search({ type: "age", minAge: 3, maxAge: 4 }));

// ===========================================
// 5. Overloading methods in classes
// ===========================================
console.log("\n=== METHODS IN CLASSES ===");

class DinosaurManager {
  private dinosaurs: Dinosaur[] = [];

  // Overloads
  add(dino: Dinosaur): void;
  add(name: string, species: string, age: number): void;

  // Implementation
  add(
    dinoOrName: Dinosaur | string,
    species?: string,
    age?: number
  ): void {
    if (typeof dinoOrName === "string") {
      this.dinosaurs.push({
        name: dinoOrName,
        species: species!,
        age: age!
      });
    } else {
      this.dinosaurs.push(dinoOrName);
    }
  }

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

  // Overloads get
  get(index: number): Dinosaur | undefined;
  get(name: string): Dinosaur | undefined;

  // Implementation
  get(indexOrName: number | string): Dinosaur | undefined {
    if (typeof indexOrName === "number") {
      return this.dinosaurs[indexOrName];
    } else {
      return this.dinosaurs.find(d => d.name === indexOrName);
    }
  }
}

const manager = new DinosaurManager();
manager.add({ name: "Rexy", species: "T-Rex", age: 5 });
manager.add("Blue", "Velociraptor", 3);

console.log("Get by index:", manager.get(0));
console.log("Get by name:", manager.get("Blue"));

// ===========================================
// 6. Overloading with Generics
// ===========================================
console.log("\n=== GENERICS WITH OVERLOADING ===");

// Overloads
function process<T extends string>(value: T): string;
function process<T extends number>(value: T): number;
function process<T extends boolean>(value: T): boolean;

// Implementation
function process<T extends string | number | boolean>(
  value: T
): string | number | boolean {
  if (typeof value === "string") {
    return value.toUpperCase();
  } else if (typeof value === "number") {
    return value * 2;
  } else {
    return !value;
  }
}

console.log("Process string:", process("hello"));
console.log("Process number:", process(21));
console.log("Process boolean:", process(true));

// ===========================================
// 7. Advanced overloading
// ===========================================
console.log("\n=== ADVANCED OVERLOADING ===");

interface FeedOptions {
  type: "scheduled";
  time: Date;
}

interface EmergencyFeedOptions {
  type: "emergency";
  reason: string;
}

// Overloads
function feedDinosaur(
  dinosaur: Dinosaur,
  amount: number
): void;

function feedDinosaur(
  dinosaur: Dinosaur,
  amount: number,
  options: FeedOptions
): void;

function feedDinosaur(
  dinosaur: Dinosaur,
  amount: number,
  options: EmergencyFeedOptions
): void;

// Implementation
function feedDinosaur(
  dinosaur: Dinosaur,
  amount: number,
  options?: FeedOptions | EmergencyFeedOptions
): void {
  if (!options) {
    console.log(`Feeding ${dinosaur.name} with ${amount}kg`);
  } else if (options.type === "scheduled") {
    console.log(`Scheduled feeding for ${dinosaur.name} at ${options.time.toISOString()}`);
  } else {
    console.log(`Emergency feeding for ${dinosaur.name}: ${options.reason}`);
  }
}

const trex = { name: "Rexy", species: "T-Rex", age: 5 };

feedDinosaur(trex, 400);
feedDinosaur(trex, 400, { type: "scheduled", time: new Date() });
feedDinosaur(trex, 600, { type: "emergency", reason: "Very hungry" });

// ===========================================
// 8. Constructor overloading
// ===========================================
console.log("\n=== CONSTRUCTORS ===");

class Paddock {
  id: string;
  name: string;
  capacity: number;

  // Constructor overloads (syntactically)
  constructor(id: string);
  constructor(id: string, name: string);
  constructor(id: string, name: string, capacity: number);

  // Implementation
  constructor(id: string, name?: string, capacity?: number) {
    this.id = id;
    this.name = name || `Paddock ${id}`;
    this.capacity = capacity || 10;
  }

  getInfo(): string {
    return `${this.name} (ID: ${this.id}, Capacity: ${this.capacity})`;
  }
}

const paddock1 = new Paddock("P-01");
const paddock2 = new Paddock("P-02", "T-Rex Territory");
const paddock3 = new Paddock("P-03", "Raptor Pen", 5);

console.log(paddock1.getInfo());
console.log(paddock2.getInfo());
console.log(paddock3.getInfo());

// ===========================================
// 9. Overloading with Promise
// ===========================================
console.log("\n=== OVERLOADING WITH PROMISE ===");

// Overloads
function fetchData(sync: true): Dinosaur;
function fetchData(sync: false): Promise<Dinosaur>;

// Implementation
function fetchData(sync: boolean): Dinosaur | Promise<Dinosaur> {
  const dino: Dinosaur = {
    name: "Rexy",
    species: "T-Rex",
    age: 5
  };

  if (sync) {
    return dino;
  } else {
    return Promise.resolve(dino);
  }
}

const syncData = fetchData(true);
console.log("Sync data:", syncData);

fetchData(false).then(asyncData => {
  console.log("Async data:", asyncData);
});

// ===========================================
// 10. Summary
// ===========================================
console.log("\n=== SUMMARY ===");
console.log("Basic overloading - different signatures");
console.log("Different parameters - optional arguments");
console.log("Different return types - the type depends on the parameters");
console.log("Objects - discriminated unions");
console.log("Methods in classes - method overloading");
console.log("Generics - overloading with generic types");
console.log("Constructors - constructor overloading");
console.log("Promise - synchronous vs asynchronous");

console.log("\nFunction overloading 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 function overloading in TypeScript?

  2. 2. How many implementation signatures can an overloaded function have in TypeScript?

These are 2 of 4 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create an overloaded findDino function that accepts an id (number) or name (string) and returns the appropriate result.

  • Click in order

    Arrange the elements of an overloaded function in TypeScript:

  • Code editor

    Create a function that takes a parameter of type string | number and uses typeof as a type guard to return the appropriate dinosaur description.

  • Vertical ordering

    Order interfaces from most general (base) to most specific (extending):

  • Click in order

    Arrange the elements of the overloaded findDino function declaration in TypeScript:

  1. QuestionWhat is Function Overloading
  2. QuestionImplementation Signature
  3. Coding taskPractice: Function Overloading
  4. Click in orderSorting: Function Overloading Syntax
  5. QuestionGeneric Type vs Type Alias
  6. QuestionInterface vs Type Alias
  7. Coding taskUnion Type with Type Guard
  8. Put in orderInterface Extension Order
  9. Click in orderOverloaded Function Signature

Useful articles