G
G
GeorgeKay2021-09-19 00:26:04
typescript
GeorgeKay, 2021-09-19 00:26:04

TypeScript throws an error, overload signature is incompatible with implementation signature. How to fix the code?

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

interface MyPositionWithDefault extends MyPosition {
  default: string
}

function position(): MyPosition
function position(a: number): MyPositionWithDefault
function position(a: number, b: number): MyPosition

function position(a?: number, b?: number) {
  if (!a && !b) {
    return {x: undefined, y: undefined}
  }

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

  return {x: a, y: b}
}

console.log('Empty: ', position())
console.log('One param: ', position(42))
console.log('Two params: ', position(10, 15))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-09-19
@vabka

Xs why it gives such an error, but if you describe the return type of the function implementation, then the error will disappear:

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

interface MyPositionWithDefault extends MyPosition {
  default: string
}

function position(): MyPosition;
function position(a: number, b: number): MyPosition;

function position(a: number): MyPositionWithDefault;

function position(a?: number, b?: number): MyPosition | MyPositionWithDefault { // вот тут
  if (a===undefined && b===undefined) {
    return {x: undefined, y: undefined}
  }

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

  return {x: a, y: b}
}

console.log('Empty: ', position())
console.log('One param: ', position(42))
console.log('Two params: ', position(10, 15))

playground

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question