8. Arrays & Tuples
Structuring Collections of Data
Variables holding single strings or numbers are useful, but applications require lists. A shopping cart holds a list of items. A class holds a list of students. In TypeScript, we must strictly define what type of data is allowed inside these arrays.
Defining Arrays
There are two primary ways to define an array in TypeScript. The most common syntax is adding square brackets [] immediately after the data type.
The Alternative Syntax (Generic Arrays)
You can also define arrays using the `Array
Empty Arrays and Type Inference
If you initialize an empty array and don't give it a type, TypeScript is forced to guess. By default, it will guess `any[]`, which defeats the purpose of TypeScript. You must explicitly type empty arrays.
Tuples: Fixed Length, Fixed Order
Standard arrays can be infinitely long, and all items are the same type. But what if you need an array where the first item is always a string, the second is always a number, and it can never be longer than 2 items? This is called a Tuple.
Where are Tuples used?
Tuples are heavily used in modern frameworks like React. The famous useState hook returns exactly a tuple: the first item is the state variable, and the second item is the setter function.
Knowledge Check
Ready to test your understanding of 8. Arrays & Tuples?