Greetings, future TypeScript Voyager! Today, we're plunging into the cosmos of tuples and arrays within TypeScript. In programming terms, a tuple is like a box filled with different star samples — they are ordered, and different elements can be of distinct types. By the end of this lesson, we will be equipped to design, access, and maneuver TypeScript tuples and arrays proficiently.
Visualize a tuple, or an array, as a star system in which each celestial body bears a distinctive characteristic. Here are a couple of methods to craft this cosmic system:
- Using brackets for arrays:
- Using generic syntax for arrays:
- Using brackets with a specific tuple type for tuples:
Both techniques efficiently generate a tuple or array; opt for the one that best suits your needs!
Indexes in tuples and arrays are like galactic maps. Each element in a tuple/array has an index that starts from 0.
The .indexOf() method helps us pinpoint the index of "Mars" within the planets array.
Measuring the length of a tuple or list can be likened to gauging the distance between galaxies. TypeScript uses the .length property for this purpose:
It couldn't be simpler!
