Разрушение с перегрузкой функций - PullRequest
0 голосов
/ 16 января 2019

Я пытаюсь создать функцию, которая принимает пару координат или объект со свойствами x и y и возвращает список соседей. Но по какой-то причине я не могу деструктурировать объект, даже когда проверил его тип:

interface Coords {
  x: number;
  y: number;
}

public getNeighbours(coords: Coords): Coords[];
public getNeighbours(x: number, y: number): Coords[];
public getNeighbours(a: number | Coords, b?: number): Coords[] {
  let x: number;
  let y: number;
  if (typeof a === 'object') {
    { x, y } = a as Coords; // failing
  } else {
    x = a;
    y = b as number;
  }
  const result = [{ x: x - 1, y }, { x: x + 1, y }, { x, y: y - 1 }, { x, y: y + 1 }];
  return result;
}

Конечно, я могу просто использовать x = a.x; y = a.y;, но мне интересно - как я могу заставить эту деструктуризацию работать?

Ответы [ 3 ]

0 голосов
/ 16 января 2019
need to destructuring declaration and to access global scope use var instead of let.

public getNeighbours(coords: Coords): Coords[];
public getNeighbours(x: number, y: number): Coords[];

public getNeighbours(a: number | Coords, b?: number): Coords[] {
// let x: number;
// let y: number;
if (typeof a === 'object') {
   var {x, y} = a as Coords; // A destructuring declaration must have an initializer
   x = x;
   y = y;
   console.log('inside destructuring: ', x, y);
 } else {
    x = a;
    y = b as number;
 }
 console.log('outside destructuring: ', x,y);
 const result = [{ x: x - 1, y }, { x: x + 1, y }, { x, y: y - 1 }, { x, y: y + 1 }];
 return result;
}

проверьте здесь Пример StackBlitz

можно избежать var и объявить объект глобально.

public getNeighbours(coords: Coords): Coords[];
public getNeighbours(x: number, y: number): Coords[];

public getNeighbours(a: number | Coords, b?: number): Coords[] {
 // let x: number;
 // let y: number;
 let globalStorage: any = {};
 if (typeof a === 'object') {
   let {x, y} = a as Coords; // A destructuring declaration must have an initializer
   globalStorage.x = x;
   globalStorage.y = y;
   console.log('inside destructuring: ', x, y);
  } else {
    globalStorage.x = a;
    globalStorage.y = b as number;
  }
 console.log('outside destructuring: ', globalStorage);
 const result = [{ x: globalStorage.x - 1, y:globalStorage.y }, { x: globalStorage.x + 1, y:globalStorage.y }, { x: globalStorage.x, y: globalStorage.y - 1 }, { x: globalStorage.x, y: globalStorage.y + 1 }];
 return result;
}
0 голосов
/ 16 января 2019

Кажется немного сложным, почему бы просто не изменить логику, мне кажется более читабельным.

CodePen.IO Пример

console.clear();
class Foo
{
  getNeighbours(coords: ICoords): ICoords[]; 
  getNeighbours(x: number, y: number) : ICoords[];
  getNeighbours(coords: number | ICoords, y?: number) : ICoords[]{
    if (typeof coords !=="object") {
      coords = { x: coords, y: y};
    }
    const result = [
      { x: coords.x - 1, y: coords.y }, 
      { x: coords.x + 1, y: coords.y }, 
      { x: coords.x, y: coords.y - 1 }, 
      { x: coords.x, y: coords.y + 1 }];
    return result;
  }
}

interface ICoords {
  x: number;
  y: number;
}

let foo = new Foo();
//debugger;
console.log(foo.getNeighbours(1,1));
console.log(foo.getNeighbours({x:1,y:1}));
0 голосов
/ 16 января 2019

Перед вашей деструктуризацией отсутствует let.

   let { x, y } = a as Coords;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...