typescriptoverloading

Typescript This overload signature is not compatible with its implementation signature


function overloading

I wrote the 2 interfaces. Also I wrote 3 overloading functions. And I have implementation of functions. And here an error - This overload signature is not compatible with its implementation signature

interface MyPosition {
  x: number | undefined
  y: number | undefined
}

interface MyPositionWithDefault extends MyPosition {
  default: string
}

function position(): MyPosition
function position(a: number): MyPositionWithDefault // Here`s an 
//error
function position(a: number, b: number): MyPosition
function position(a?: number, b?: number) {
  if (!a && !b) {
    return {x: undefined, u: undefined}
  }

  if (a && !b) {
    return {x: a, y: undefined, default: a.toString}
  }

  return {x: a, y: b}
}

Playground


Solution

  • The compiler for some reason cannot infer the correct return type, simply adding the annotation fixes the problem:

    interface MyPosition {
      x: number | undefined
      y: number | undefined
    }
    
    interface MyPositionWithDefault extends MyPosition {
      default: string
    }
    
    function position(): MyPosition
    function position(a: number): MyPositionWithDefault // No error
    function position(a: number, b: number): MyPosition
    function position(a?: number, b?: number): MyPosition | MyPositionWithDefault { // added return type annotation
      if (!a && !b) {
        return {x: undefined, y: undefined}
      }
    
      if (a && !b) {
        return {x: a, y: undefined, default: a.toString() }
      }
    
      return {x: a, y: b}
    }
    

    Playground

    I also cleaned up some typos.