@GeorgeKay

TypeScript выдает ошибку, сигнатура перегрузки несовместима с сигнатурой реализации. Как исправить код?

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))
  • Вопрос задан
  • 324 просмотра
Пригласить эксперта
Ответы на вопрос 1
vabka
@vabka
Токсичный шарпист
Хз почему выдаёт такую ошибку, но если описать возвращаемый тип у реализации функции, то ошибка пропадёт:
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
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы