Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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[]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading