Arrays and Tuples
Typing collections of values
Introduction
In this lesson, you'll learn about arrays and tuples in TypeScript. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, you're familiar with typing collections of values.
TypeScript has its own approach to typing collections of values, which we'll explore step by step.
The TypeScript Way
Let's see how TypeScript handles this concept. Here's a typical example:
// TypeScript arrays
let numbers: number[] = [1, 2, 3];
let mixed: (number | string | boolean)[] = [1, "two", true];
// Array methods are type-safe
numbers.push(4);
let doubled: number[] = numbers.map(n => n * 2);
// Tuples for fixed-length, typed arrays
let point: [number, number] = [10, 20];Comparing to JavaScript
Here's how you might have written similar code in JavaScript:
// JavaScript arrays
let numbers = [1, 2, 3];
let mixed = [1, "two", true];
// Array methods
numbers.push(4);
let doubled = numbers.map(n => n * 2);
// Fixed-length arrays
let point = [10, 20]; // x, y coordinatesYou may be used to different syntax or behavior.
Array types use Type[] or Array<Type> syntax
You may be used to different syntax or behavior.
Union types (|) allow multiple types in arrays
You may be used to different syntax or behavior.
Tuples define fixed-length arrays with specific types per position
Step-by-Step Breakdown
1. Array Type Syntax
TypeScript offers two equivalent syntaxes for array types.
let items = [1, 2, 3];let items: number[] = [1, 2, 3];
// or
let items: Array<number> = [1, 2, 3];2. Union Type Arrays
When an array can contain multiple types, use a union type.
let data = [1, "hello", true];let data: (number | string | boolean)[] = [1, "hello", true];3. Tuples
Tuples are fixed-length arrays where each position has a specific type. They're useful for representing structured data.
let coord = [10, 20]; // JS: just an arraylet coord: [number, number] = [10, 20];
let user: [string, number] = ["Alice", 30];Common Mistakes
When coming from JavaScript, developers often make these mistakes:
- Array types use Type[] or Array<Type> syntax
- Union types (|) allow multiple types in arrays
- Tuples define fixed-length arrays with specific types per position
Key Takeaways
- Use Type[] for homogeneous arrays
- Use union types for mixed arrays
- Use tuples for fixed-length, positionally-typed arrays