Destructuring with function overloading

Solution 1:

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;
}

check here StackBlitz example

can be avoid var and declare object as globally..

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;
}

Solution 2:

Seems a bit complicated, why not just reverse the logic, seems more readable to me.

CodePen.IO Example

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}));