Simple Overload Example
You'll learn how to write a function that returns different types based on what you pass in.
Sometimes a function's return type depends entirely on its input. For example, imagine a getItem function: if you pass it a number, it returns a string; if you pass it a string, it returns a number. How do you tell TypeScript about this relationship?
The Problem Without Overloads
Without overloads, you'd get a union return type that's too loose:
function getItem(key: string | number): string | number {
if (typeof key === "number") {
return "Item " + key;
} else {
return key.length;
}
}
const result = getItem(5); // Type: string | number
// TypeScript doesn't know it's specifically a string
Writing Your First Overload
Function overloads let you declare exact input-output pairs:
// Overload signature 1: number → string
function getItem(key: number): string;
// Overload signature 2: string → number
function getItem(key: string): number;
// Implementation signature (must handle all cases)
function getItem(key: string | number): string | number {
if (typeof key === "number") {
return "Item " + key;
} else {
return key.length;
}
}
const result1 = getItem(5); // Type: string ✓
const result2 = getItem("hello"); // Type: number ✓
Now TypeScript knows exactly what you'll get back based on what you put in. The overload signatures appear first, followed by the implementation. Only the overload signatures are visible to callers—the implementation signature is internal.
Key Takeaway: Function overloads let you specify precise input-to-output type relationships, giving callers better type information than a generic union return type.