Day 3: Arrays and Tuples
Managing Lists of Data
Welcome to Day 3! We’ve covered the basic primitives. Now let’s talk about collections. Most apps aren’t just single numbers or strings; they are lists of things.
Arrays
In TypeScript, there are two main ways to define an array.
Syntax 1: type[]
This is the most common syntax.
let numbers: number[] = [1, 2, 3, 4, 5];
let names: string[] = ["Alice", "Bob", "Charlie"];
Syntax 2: Array<type>
This uses the generic syntax (we’ll cover Generics deeply later).
let scores: Array<number> = [95, 82, 76];
Avoid any[]: Try not to use any[] (mixed arrays) unless absolutely necessary. It defeats the purpose of TypeScript.
Tuples
What if you need an array with a fixed number of elements, where each element has a specific type? That’s a Tuple.
Imagine representing a user record with an ID (number) and a Name (string).
// Define a tuple
let user: [number, string];
// Initialize it
user = [1, "Jack"]; // OK
// user = ["Jack", 1]; // Error: Type 'string' is not assignable to type 'number'.
Tuples are great for returning multiple values from a function or working with CSV-like data rows.
let rgb: [number, number, number] = [255, 0, 0];
Readonly Tuples
You can make tuples immutable (unchangeable).
let point: readonly [number, number] = [10, 20];
// point[0] = 5; // Error!
Challenge for Today
- Create a file
day3.ts. - Define an array of your favorite hobbies (strings).
- Define a tuple that represents a “Person”:
[name (string), age (number), isStudent (boolean)]. - Try to add a fourth element to your tuple and see what happens (concept: fixed length).
- Log the person’s name from the tuple.
See you on Day 4!