Intersection Types Merge Function Overloads
Combine call signatures with an intersection type, implement one runtime function, and call the overloaded converter with string, number, and boolean.
Code
// An intersection type merges call signatures into function overloads.
type Converter =
& ((value: string) => string)
& ((value: number) => number)
& ((value: boolean) => string);
function convert(value: string): string;
function convert(value: number): number;
function convert(value: boolean): string;
function convert(value: string | number | boolean): string | number {
if (typeof value === "number") {
return value * 2;
}
if (typeof value === "boolean") {
return value ? "yes" : "no";
}
return value.trim().toLowerCase();
}
const converter: Converter = convert;
console.log(converter(" Hello "));
console.log(converter(21));
console.log(converter(true));
console.log("signatures:", 3);Output
Captured from a sandboxed run of this snippet in the build pipeline.
hello
42
yes
signatures: 3How it works
The conversion itself happens in convert — everything else is wiring.
What to watch for
- The imports (if any) point only at standard-library modules.
- The guard
typeof value === "number"short-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Signature: function convert(value: string)
Output lines are prefixed (signatures:), making each step’s effect easy to spot.
Statements that matter
return value.trim().toLowerCase();
& ((value: boolean) => string);
return value ? "yes" : "no";
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. The file defines `convert` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.