Home > Net >  Why Type 'never[]' is not assignable to type 'number'
Why Type 'never[]' is not assignable to type 'number'

Time:11-14

I need to fill in the binary matrix.

const matrix: number[][] = [];

for (let i = 0; i < 7; i  ) {
  for (let j = 0; j < 7; j  ) {
    if (!matrix[i]) matrix[i] = [];

    if (!matrix[i][j]) matrix[i][j] = []; //here is TS exception
    matrix[i][j] = 1;
  }
}

the line matrix[i][j] = [] - throw a TS exception - Type 'never[]' is not assignable to type 'number'.ts(2322)***.

What should I do to avoid it?

CodePudding user response:

The error is caused because you try to assign an empty array (never[]) to number as the error describes. Based off of your original matrix variable being a 2D array, this means that the 2nd check you have is useless and you can remove it.

const matrix: number[][] = [];

for (let i = 0; i < 7; i  ) {
  for (let j = 0; j < 7; j  ) {
    if (!matrix[i]) matrix[i] = [];

    // useless (and invalid) check!
    // if (!matrix[i][j]) matrix[i][j] = []; 

    matrix[i][j] = 1;
  }
}

Typescript Playground

The reason why an empty array is the type never[] is because of it's freshness. If it was a variable, say:

const arr = []
//    ^? -- any[]

it would count as any[]. But since you're explicitly adding it to the array as an empty array, since it's fresh, it immideately uses what the type really is at assignment: never[]

  • Related