3

I have the following types:

export type Point = [number, number];
export type LineType = [Point, Point];

export const hexPoint = (x: number, y: number, p: number): Point => {
  const [px, py] = coordinateToPoint(x, y);
  return [
    px + Math.cos((Math.PI * 2 * p) / 6) * size,
    py + Math.sin((Math.PI * 2 * p) / 6) * size,
  ];
};

const center = (point: Point): Point => {
  point[0] += w / 2;
  point[1] += h / 2;
  return point;
};

export const hexLineTop = (x: number, y: number): LineType => [
  hexPoint(x, y, 4),
  hexPoint(x, y, 5),
];

const constructHexagonalGrid = (points: [number, number][]): LineType[] => {
  let lines: LineType[] = [];
  points.forEach((point) => {
    lines.push(hexLineTop(...point).map(center));
  });
});

The line I'm struggling with is this one:

lines.push(hexLineTop(...point).map(center));

If I remove the .map... it all works OK:

lines.push(hexLineTop(...point));

But the line I'm using now (which modifies the location of the points) gives the error:

Argument of type 'Point[]' is not assignable to parameter of type 'LineType'. Target requires 2 element(s) but source may have fewer.ts(2345) const center: (point: Point) => Point

I'm not sure of the syntax to make the map work. I've tried:

lines.push(hexLineTop(...point).map<LineType>(center));

and:

lines.push(hexLineTop(...point).map(center):LineType);
Djave
  • 8,595
  • 8
  • 70
  • 124
  • 2
    You may need to explicitly cast it, as apparently typescript does not care about array length when mapping. maybe an explicit `as LineType` would work? – DownloadPizza Dec 29 '21 at 11:39
  • 1
    fastest solution: `lines.push(hexLineTop(...point).map(center) as LineType);` – DDomen Dec 29 '21 at 11:46
  • The `Array.prototype.map()` typings in TypeScript don't map tuples to tuples, so If you want this you have to use a type assertion or possibly merge in your own typings for `map()` (but that's not likely worth it). See [this answer](https://stackoverflow.com/a/57913509/2887218) for more info. – jcalz Dec 29 '21 at 14:04

0 Answers0