Arrays and tuples
| string[] syntax | |
| Array<string> form | |
| Fixed tuples | |
| Readonly arrays |
string[] syntax
An array type names the item type followed by square brackets. Every item must match, so a stray number among strings stops the compile at once:
const tags: string[] = ["ts", "types"];
console.log(tags.length);
2
The tags array holds exactly two strings, so length reports 2. Pushing a number into tags would fail before the program ever runs.
Array<string> form
The same array can be written in generic form with the item type inside angle brackets. Both spellings mean the same thing, so teams pick one and stay with it:
const scores: Array<number> = [10, 20];
console.log(scores[0]);
10
Index zero holds 10, which the program prints. The short string[] spelling dominates simple cases, while the generic spelling shines inside complex nested types.
Fixed tuples
A tuple fixes both the length and the type of each slot. It fits pairs like coordinates, where position zero and position one play different roles:
const point: [number, number] = [10, 20];
console.log(point[0] + point[1]);
30
Swapping in a third item or a string would break the compile. Use tuples for short fixed records and plain arrays for collections of unknown length.
Readonly arrays
The readonly marker freezes an array at compile time. Reading stays free, while push and direct index writes are rejected before they can corrupt shared data:
const nums: readonly number[] = [1, 2, 3];
console.log(nums.length);
3
Mark arrays readonly when a function only needs to read them. Callers keep full control of their data, and accidents turn into compile errors instead of silent bugs.
Next: Type aliases
Article author: Arthur Isaev