How to use array.map with tuples in typescript?

TypeScript does not attempt to preserve tuple length upon calling map(). This feature was requested in microsoft/TypeScript#11312, implemented in microsoft/TypeScript#11252, and reverted in microsoft/TypeScript#16223 due to problems it caused with real world code. See microsoft/TypeScript#29841 for details.

But if you want, you could merge in your own declaration for the signature of Array.prototype.map(), to account for the fact that it preserves the length of tuples. Here’s one way to do it:

interface Array<T> {
  map<U>(
    callbackfn: (value: T, index: number, array: T[]) => U,
    thisArg?: any
  ): { [K in keyof this]: U };
}

This uses polymorphic this types as well as array/tuple mapped types to represent the transformation.

Then your code could be written like the following:

function applyMove(board: Board): Board {
  return board.map(
    (row: Three, index: number) => (index === 0 ? applyMoveToRow(row) : row)
  );
}

function applyMoveToRow(row: Three): Three {
  return [2, row[1], row[2]];
}

and there’d be no error. Note that I didn’t bother trying to deal with Array.prototype.slice(). It would be a large amount of effort to try to represent what slice() does to a tuple type, especially since there’s no real support for tuple length manipulation… meaning you might need a bunch of overload signatures or other type trickery to get it done. If you’re only going to use slice() for short arrays, you might as well just use index access like I did above with [2, row[1], row[2]] which the compiler does understand.

Or if you’re going to use it for longer arrays but a small number of times in your code, you might just want to use a type assertion to tell the compiler that you know what you’re doing. For that matter, if you’re only doing map() a small number of times, you can use a type assertion here too instead of the above redeclaration of map()‘s signature:

function applyMove(board: Board): Board {
  return board.map(
    (row: Three, index: number) => (index === 0 ? applyMoveToRow(row) : row)
  ) as Board; // assert here instead of redeclaring `map()` method signature
}

Either way works… type assertions are less type safe but more straightforward, while the declaration merge is safer but more complicated.

Hope that helps; good luck!

Link to code

Leave a Comment