Cover photo credit: An article by Johnny Simpson
Introduction
Arrays in Typescript don't have much attached to them, but behind the scenes there is more to their working than how arrays function in Javascript. In this article, you'll learn about the complexities and benefits TS brings to the workings of arrays.
Array Types
Besides specifying an array in TS, we can also specify the content that arrays can have, but first, observe a strange behavior of arrays in TS. If an array is declared like :
const houses = [];
houses.push("bungalow")
houses
implicitly carries a data type,never
, and cannot carry out array methods likepush
.never
implies that the data type should never be mutated, and this will lead to an error.
To stop this, simply specify the array like the second line, because specifying an array like the first line implies that the array should always be empty and will induce static checking errors.
const houses: [] = [];
const superHouses: string[] = [];
const superHousesAndLevels : string[] & number[] = []
superHouses.push("Cave Glass Houses");
superHousesAndLevels.push("etch skyscrappers")
superHousesAndLevels.push(45)
The
houses
declaration still imply the never type.superHouses
on the other hand implies the type of contents the array should have;superHousesAndLevels
allows for the contents of the array to be both strings and numbers. With as many parameter data types as you want.
You can also specify that an array should have only arrays inside it:
const Coordinates : number[][] = [
[638,7834]
]
Coordinates
should only have an array that has arrays with numbers inside.
Array Aliases
In the same way, type aliases can be used for variables, is the same way it can be used in arrays.
type User = {
name : string;
isActive : boolean;
}
const allUsers : User[] = []
allUsers.push({name: "", isActive: true});
a
User
alias is declared, with two parameters.allUsers
is defined with theUser
alias, and parameters are typed withUser
guidelines.
Readonly Arrays
The ReadonlyArray
is a special TS type that describes arrays that should not be changed:
const immutableArray : ReadonlyArray<String> = [
"shakan","awa","sheikunude"
]
immutableArray.push("yyy") // static error
- The
immutableArray
is described to be unchangeable in parts of the code,and when we call a method to update the array, TS static checking signals an error.
Conclusion
Obviously, this is not all to arrays, but should get you started with using arrays to ensure clean code and type safety in your code bases.