Union Signatures as an Alternative
You'll learn: How to replace multiple function overload declarations with a single signature that uses union types for parameters and return values.
What This Means
When you have a function that behaves differently based on input types, you've seen that function overloads let you declare multiple call signatures. But there's often a simpler alternative: write one signature with union types in the parameter and return positions.
Instead of stacking multiple type declarations, you declare what the function actually does: it accepts multiple possible input types and returns multiple possible output types. TypeScript's type system is smart enough to track which return type corresponds to which input.
The Pattern
Rather than:
function process(value: string): string;
function process(value: number): number;
function process(value: string | number): string | number {
// implementation
}
You can write:
function process(value: string | number): string | number {
if (typeof value === "string") {
return value.toUpperCase(); // returns string
}
return value * 2; // returns number
}
Both approaches work, but the union signature is more concise when the relationship between input and output is straightforward.
When Union Signatures Shine
Union signatures work best when:
- The function logic is simple and doesn't need strict input-output pairing
- You're okay with the return type being a union (the caller narrows it)
- You want less ceremony and fewer lines of code
The Trade-off
The overload approach gives you tighter type relationships—TypeScript knows that string input produces string output. With union signatures, the return type is string | number regardless of input, so callers must narrow it themselves.
Key Takeaway: Union signatures replace overloads with a single, simpler signature using union types—great for straightforward cases, but less precise about input-output type correspondence than explicit overloads.