Function Overloads in .d.ts
What you'll learn: How to declare multiple function signatures in declaration files to accurately describe JavaScript libraries with overloaded behavior.
Why This Matters in Declaration Files
Many JavaScript libraries have functions that behave differently based on the number or types of arguments passed. When you're writing a .d.ts file to provide types for such a library, you need a way to express these different call signatures. That's where function overloads in declaration files come in.
Unlike function overloads in regular TypeScript code (where you have both signatures and an implementation), declaration files only contain the signatures — because the actual JavaScript implementation lives elsewhere.
Basic Syntax in .d.ts Files
In a declaration file, you simply list all the overload signatures without any implementation:
// mylibrary.d.ts
export declare function parseData(input: string): object;
export declare function parseData(input: number): string;
export declare function parseData(input: boolean): number;
Notice there's no implementation signature here — declaration files describe types, not behavior.
Real-World Pattern: Optional Parameters Alternative
Many JavaScript functions accept different argument combinations. Instead of using optional parameters (which sometimes aren't precise enough), overloads let you be explicit:
// Before: Less precise
declare function createElement(tag: string, props?: object): Element;
// After: More precise with overloads
declare function createElement(tag: string): Element;
declare function createElement(tag: string, props: object): Element;
The second version makes it clear that props is truly optional, and each signature represents a distinct, valid way to call the function.
Describing Return Type Variations
Overloads shine when the return type depends on the input type:
declare function getValue(key: "count"): number;
declare function getValue(key: "name"): string;
declare function getValue(key: "active"): boolean;
This gives you perfect autocomplete and type safety based on which literal string you pass.
Key Takeaway: Function overloads in .d.ts files let you declare multiple type signatures for JavaScript functions without providing implementations, enabling precise typing of libraries with flexible calling patterns.