Overloads, Call Signatures, and this Parameter - Textnotes

Overloads, Call Signatures, and this Parameter


Learn advanced function typing techniques in TypeScript to create flexible and type-safe functions. This module explains function overloads, call signatures, and typing the this parameter with practical examples.

1. Function Overloads

Function overloads allow you to define multiple type signatures for a single function. This helps handle different input types while maintaining type safety.

Basic Example


function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}

let sum = add(10, 20); // number
let concatenated = add("Hi, ", "Muni"); // string

Overloads provide type-safe behavior for functions with multiple input variations.

2. Call Signatures

Call signatures describe the type of a function, including parameter types and return types, without defining the implementation.

Example


interface MathOperation {
(x: number, y: number): number;
}

const multiply: MathOperation = (a, b) => a * b;

let result = multiply(5, 10); // 50

Call signatures are useful for typing callbacks, function parameters, or APIs.

Example with Optional Parameters


interface Logger {
(message: string, level?: "info" | "warn" | "error"): void;
}

const log: Logger = (msg, level = "info") => console.log(`[${level}] ${msg}`);
log("Server started"); // [info] Server started

3. this Parameter Typing

TypeScript allows typing the this parameter for functions, which is useful in classes or objects to ensure type-safe this usage.

Example in Object


interface User {
name: string;
greet(this: User, greeting: string): void;
}

const user: User = {
name: "Muni",
greet(this: User, greeting: string) {
console.log(`${greeting}, ${this.name}`);
}
};

user.greet("Hello"); // Hello, Muni

Example in Classes


class Counter {
count = 0;
increment(this: Counter) {
this.count++;
}
}

const counter = new Counter();
counter.increment();
console.log(counter.count); // 1

Typing this prevents errors when functions are called with the wrong context.

Conclusion

Advanced function typing in TypeScript enhances flexibility and type safety. Function overloads, call signatures, and this parameter typing allow developers to define complex and reusable function patterns while reducing runtime errors and improving code clarity.