TypeScript
/Beginner
Array Types & Tuples
Definition
Defining the type of elements that an array is allowed to hold. Tuples are a special type of array with a fixed length and specific types at specific indexes.
Explain Like I'm New
An Array Type says: 'This box can hold an infinite number of Strings, but absolutely NO numbers'. A Tuple says: 'This box holds exactly two things: the first must be a String, the second must be a Number.'
Real World Example
Typing a list of string IDs: `string[]`. Typing the return value of React's `useState`: `[number, (val: number) => void]`. This is a classic Tuple!
Common Use Cases
- •Lists of data
- •React hooks returns (Tuples)
- •CSV data rows
Interactive Example
// Standard Array const names: string[] = ["Alice", "Bob", "Charlie"]; // names.push(5); // Error! // Array of Objects const users: { id: number }[] = [{ id: 1 }, { id: 2 }]; // TUPLE: Fixed length, strict order let coordinates: [string, number, number] = ["New York", 40.71, -74.00]; // coordinates = [40.71, "New York", -74.00]; // Error: Types are out of order!
Interview Questions
basic
- What are the two syntaxes for typing an array?
intermediate
- What is a Tuple?
advanced
- Can you push a new element into a Tuple?