Search code examples
typescriptfunctionoverloading

Typescript function overloading doesn't work


The error is

Type '(str: string, convert?: unknown) => { result: number; } | { result: string; }' is not assignable to type 'X'.
  Type '{ result: number; } | { result: string; }' is not assignable to type '{ result: string; }'.
    Type '{ result: number; }' is not assignable to type '{ result: string; }'.
      Types of property 'result' are incompatible.
        Type 'number' is not assignable to type 'string'.
interface X {
    (str: string): {
        result: string
    }
    (str: string, convert: true): {
        result: number
    }
}

const func: X = (str, convert = false) => {
    if (convert) return {
        result: parseInt(str, 10)
    }

    return {
        result: str
    }
}

Playground


Solution

  • Function overloads are just function signatures above the concrete implementation. These are syntactic sugars to allow typing of a function that has dynamic arguments.

    In JavaScript a function can be written to accept a parameter of mixed types. TypeScript overloads allow statically typing of these dynamic uses of JavaScript functions.

    function x(str: string): string;
    function x(str: string, convert: true): number;
    function x(str: string, convert?: boolean) {
      if (convert) {
        return parseInt(str, 10);
      }
    
      return str;
    }