Type error: Type ‘string’ is not assignable to type ‘number’

When you create an array in TypeScript the type of the first element defines the type of all elements of the array.

When we reuse an array with new data, the array type has already been defined, so when we assign new values to the same array we get the error message:

Type error: Type ‘string’ is not assignable to type ‘number’

If the array only contained one type of data during definition, all elements will be defined as that data type.

let myArray = [1, 2, 3, 4, 5];
// error: Type 'string' is not assignable to type 'number' 
myArray = ['1', '2', '3', '4', '5']; 

If the array definition contained mixed data type, the elements will be defined as “objects”.

let myArray = [1, 'a', 3, 4, 5];
// No error 
myArray = ['b', 6, 'd', 7, 'f']; 

Leave a comment

Your email address will not be published. Required fields are marked *