Arrays in TypeScript
Description
Arrays can be written in TypeScript like this;
let colors = ['red', 'blue', 'green'];
//TypeScript automatically infers the type of array on the colors variable because the value is a string. If the value of the colors variable is changed to a number or a different data type, an error will be produced.
//Note that since all the items in the array are all strings, typescript automatically infers the string array type on the colors variable.
//String arrays
let colors = ['red', 'blue', 'green']; //The data type is string[]
//Number arrays
let ages = [10, 20, 4, 9]; //The data type is number[]
//Mixed arrays
let mixed = ['Max', 1, true, 'Katty']; //The data type is (string | number | boolean)[]
//You can change the value of any position inside a mixed array to a string or a number. It doesn't matter what the type was initially.
//If you declare an array with a type at the start, it can only have that one type in it.
//you cannot change the data type of the variable that has been declared in arrays. If an array has been declared, the variable that owns it cannot be changed to a different data type, e.g a string. Not only are the values inside an array fixed, the type of the variable is also fixed as well.
Quick Note
- You can change the value of any position inside a mixed array to a string or a number. It doesn't matter what the type was initially.
- If you declare an array with a type at the start, it can only have that one type in it.
- You cannot change the data type of the variable that has been decaled in arrays. If an array has been declared, the variable that owns it cannot be changed to a different data type, e.g. a string. Not only are the values inside an array fixed, the type of the variable is also fixed as well.