Jolleyboy
Jolleyboy

Reputation: 1413

Why is a Typescript array of the right structure not assignable to a seemingly compatible tuple

For example:

let myTuple: Array<[number[], number[]]> = [];
const my3dArray = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]],
];
myTuple = my3dArray;

Gives the error: number[][][] not assignable to [number[], number[]][] when using TypeScript 3.0.1

Upvotes: 4

Views: 578

Answers (1)

smnbbrv
smnbbrv

Reputation: 24581

On the second line you create a variable that automatically picks up the type of the assigned value:

const my3dArray = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]],
];

The type of the assigned value is assumed to be number[][][], which is correct.

Then the value of this type (which is, again, assumed to be number[][][]) is getting assigned to a variable with a more strict type Array<[number[], number[]]> and the type from the previous operation does not pass the check. The value does not matter anymore at this point, only the generated type matters.

Explicit type assignment fixes the issue:

let myTuple: Array<[number[], number[]]> = [];

const my3dArray = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]],
] as Array<[number[], number[]]>;

myTuple = my3dArray;

or another option is defining the type of the variable before assignment:

let myTuple: Array<[number[], number[]]> = [];

const my3dArray: Array<[number[], number[]]> = [
  [[1, 2], [3, 4]],
  [[5, 6], [7, 8]],
];

myTuple = my3dArray;

Upvotes: 2

Related Questions