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

Upvotes: 2

Views: 60

Answers (2)

Alexander Nenashev
Alexander Nenashev

Reputation: 23652

  1. Your numbers could be 0 so using !a seems wrong, use type narrowing.
  2. The second overload mismatch the first so return as MyPositionWithDefault, this is more clear where this type is returned.
  3. For all other options just return MyPosition once, no need in !a && !b

Playground

function position(a?: number, b?: number) {
  
  if(typeof a === 'number' && b === undefined){
    return {x: a, y: undefined, default: a.toString()} as MyPositionWithDefault;
  }

  return {x:a, y:b};
}

Upvotes: 1

Jared Smith
Jared Smith

Reputation: 22029

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.

Upvotes: 2

Related Questions