Introduction and Lesson Objectives

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.

Foundational Tuples and Arrays: The Basics

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:
// Define array of first four planets
let planets: string[] = ["Mercury", "Venus", "Earth", "Mars"];
console.log(planets); // Prints: ["Mercury", "Venus", "Earth", "Mars"]
  • Using generic syntax for arrays:
// Define array of first four planets using generic Array type
let planetsGeneric: Array<string> = ["Mercury", "Venus", "Earth", "Mars"];
console.log(planetsGeneric); // Prints: ["Mercury", "Venus", "Earth", "Mars"]
  • Using brackets with a specific tuple type for tuples:
// Define tuple with planet and its position
let earth: [string, number] = ["Earth", 3];
console.log(earth); // Prints: ["Earth", 3]

Both techniques efficiently generate a tuple or array; opt for the one that best suits your needs!

Navigation using Indexing

Indexes in tuples and arrays are like galactic maps. Each element in a tuple/array has an index that starts from 0.

// Access third planet in the array
console.log(planets[2]);  // Prints: "Earth"

// Access first planet in the array
console.log(planets[0]);  // Prints: "Mercury"

// Find the index of 'Mars'
console.log(planets.indexOf("Mars"));  // Prints: 3

The .indexOf() method helps us pinpoint the index of "Mars" within the planets array.

Array Properties: Inclined towards length

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:

// Checks the number of planets in the array
console.log(planets.length);  // Prints: 4

It couldn't be simpler!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal