Master TypeScript From Scratch

Learn TypeScript step by step with practical examples, interactive coding lessons, and real-world projects.

Function Overloads in TypeScript

Learn how to define multiple function signatures with the same function name, handle different input types, and implement overloaded functions in TypeScript.

Simple Explanation: Function overloading allows us to define multiple ways to call a function using the same name. TypeScript selects the appropriate overload based on the arguments supplied.

What Are Function Overloads?

Function overloading allows a function to support different combinations of parameter types or parameter counts while keeping the same function name.

In TypeScript, we declare multiple overload signatures and provide one implementation that handles the supported input combinations.

  • Multiple overload signatures can use the same function name.
  • Each overload describes a supported way to call the function.
  • A single implementation handles the actual function execution.
  • The implementation must be compatible with the declared overloads.
  • Overloads help provide clearer type checking and function usage.

Function Overloading Workflow

Follow these steps to understand how TypeScript function overloading works.

📝
Step 1
Declare Overloads

Define the supported function signatures.

→
📥
Step 2
Pass Arguments

Call the function with valid arguments.

→
⚙️
Step 3
Run Implementation

Process the arguments using one implementation.

→
✅
Step 4
Return Result

Return the result for the selected overload.

Visual Example
Function Calls

formatValue(100)

formatValue("Hello")

→
Same Function

formatValue()

One implementation handles both inputs.

1. Syntax of Function Overloads

A function overload consists of overload signatures followed by a single implementation.

Syntax

function functionName(value: string): string;
function functionName(value: number): string;

function functionName(value: string | number): string {
    // Implementation
    return String(value);
}

Important Points

  • The first two declarations are overload signatures.
  • Overload signatures end with semicolons and do not contain function bodies.
  • The final declaration contains the implementation.
  • The implementation signature itself is not available as a separate public overload.
Remember: TypeScript uses the overload signatures to check function calls at compile time.

2. Overloads with Different Parameter Types

We can use overloads when a function should accept different input types and return the appropriate result.

Example

function formatValue(value: number): string;
function formatValue(value: string): string;

function formatValue(value: number | string): string {
    if (typeof value === "number") {
        return "Number: " + value;
    }

    return "Text: " + value;
}

console.log(formatValue(100));
console.log(formatValue("Hello TypeScript"));

Expected Output

Number: 100
Text: Hello TypeScript

Explanation

  • The first overload accepts a number.
  • The second overload accepts a string.
  • The implementation accepts both types through the union type number | string.
  • The typeof condition identifies which type of value was supplied.

3. Overloads with Different Numbers of Parameters

Function overloads can also support different numbers of parameters.

Example

function createMessage(name: string): string;
function createMessage(name: string, course: string): string;

function createMessage(
    name: string,
    course?: string
): string {
    if (course !== undefined) {
        return "Welcome " + name + " to " + course;
    }

    return "Welcome " + name;
}

console.log(createMessage("Rahul"));
console.log(createMessage("Priya", "TypeScript"));

Expected Output

Welcome Rahul
Welcome Priya to TypeScript

Explanation

  • One overload accepts only a name.
  • Another overload accepts a name and a course.
  • The implementation uses an optional course parameter to handle both supported calls.

4. Function Overloads with Calculations

We can define overloads to support different calculation operations using the same function name.

Example

function calculate(a: number, b: number): number;
function calculate(a: string, b: string): string;

function calculate(
    a: number | string,
    b: number | string
): number | string {
    if (typeof a === "number" && typeof b === "number") {
        return a + b;
    }

    if (typeof a === "string" && typeof b === "string") {
        return a + b;
    }

    throw new Error("Both arguments must have the same type.");
}

console.log(calculate(10, 20));
console.log(calculate("Hello ", "World"));

Expected Output

30
Hello World

Explanation

  • When both arguments are numbers, the function performs numeric addition.
  • When both arguments are strings, the function concatenates the strings.
  • The overload signatures reject unsupported combinations at compile time.

5. Understanding Overload Signatures

Overload signatures describe which calls are allowed. The implementation signature defines the code that executes those calls.

Example

function getLength(value: string): number;
function getLength(value: string[]): number;

function getLength(value: string | string[]): number {
    return value.length;
}

console.log(getLength("TypeScript"));
console.log(getLength(["Java", "Python", ".NET"]));

Expected Output

10
3

Explanation

  • A string overload accepts a string value.
  • An array overload accepts an array of strings.
  • Both strings and arrays have a length property.
  • The single implementation returns the length of the supplied value.

6. Function Overloads vs Union Types

Overloads and union types both support multiple input types, but they describe function usage differently.

Function Overloads Union Types
Declare multiple function signatures. Allow a parameter to accept multiple types.
Can describe different parameter combinations. Can express one parameter as a combination of supported types.
Can provide different return types for different overloads. A simple union-based signature may expose a union return type.
Useful when supported calls need distinct type signatures. Useful when one implementation handles multiple types with a shared signature.

7. Practical Example: CIIT Student Information

Let's create a function that retrieves student information based on a numeric student ID or a student name.

Example

function getStudentInfo(studentId: number): string;
function getStudentInfo(studentName: string): string;

function getStudentInfo(
    student: number | string
): string {
    if (typeof student === "number") {
        return "Student ID: " + student;
    }

    return "Student Name: " + student;
}

console.log(getStudentInfo(101));
console.log(getStudentInfo("Priya"));

Expected Output

Student ID: 101
Student Name: Priya

Explanation

  • The first overload accepts a student ID as a number.
  • The second overload accepts a student name as a string.
  • The implementation checks the input type and returns the corresponding student information.

Common Mistakes

  • Writing a function body for each overload signature instead of using one implementation.
  • Declaring overload signatures that are incompatible with the implementation.
  • Forgetting to handle the supported input types inside the implementation.
  • Calling the function using arguments that do not match any declared overload.
  • Assuming the implementation signature itself is available as a separate overload.
Remember: Declare all overload signatures first, then write one implementation that supports the declared calls.

Practice Task

Write TypeScript functions using overloads to complete the following tasks.

  • Create a function that accepts either a number or a string and returns a formatted message.
  • Create a function that calculates the area of a square using one argument or a rectangle using two arguments.
  • Create a function that accepts a student ID or student name and returns student information.
  • Create a function that returns the length of a string or an array of strings.
  • Create overloads for a function that combines two numbers or two strings.
Challenge: Ensure that every overload signature matches the implementation and that unsupported calls produce TypeScript errors.

Summary

In this lesson, we learned how function overloading supports multiple function signatures with the same name. We used overloads with different parameter types, different parameter counts, calculations, and a student information example. Overloads help TypeScript validate function calls and describe their expected results.