Quick Answer

Multiple function signatures for one implementation

Understanding the Issue

TypeScript allows multiple function signatures for a single implementation. The implementation must handle all cases, and callers get type-checked against the signatures.

The Problem

This code demonstrates the issue:

Typescript Error
// Problem: Multiple possible signatures
function pad(value: string, padding: number | string): string {
    // Need type checking in implementation
    return typeof padding === "number"
        ? value.padStart(padding)
        : padding + value;
}

The Solution

Here's the corrected code:

Typescript Fixed
// Solution: Overload signatures
function pad(value: string, padding: number): string;
function pad(value: string, padding: string): string;
function pad(value: string, padding: any): string {
    return typeof padding === "number"
        ? value.padStart(padding)
        : padding + value;
}

// Now callers get proper type checking
const x = pad("hi", 4); // OK
const y = pad("hi", "~"); // OK

Key Takeaways

Use overload signatures to provide better type checking for flexible functions.