Lesson 8 of 56 · Typescript
Function Overloads
Duration: 20 minutes
Overloading Signatures
When a function behaves differently based on its arguments, you can provide multiple call signatures.
function fn(x: string): string;
function fn(x: number): number;
function fn(x: any): any {
return typeof x === "string" ? x.toUpperCase() : x * 2;
}
const a = fn("hi"); // a is string
const b = fn(10); // b is number
Implementation Signature
The implementation must be compatible with all overload signatures but is not exposed to callers.
Practical Example – getElement
function getElement(id: string): HTMLElement | null;
function getElement<T extends HTMLElement>(selector: string, type: { new(): T }): T | null;
function getElement(arg1: any, arg2?: any): any {
// runtime logic …
}