Objects, Arrays & Tuples
๐ฆ Objects, Arrays & Tuples
๐ Object Types
Basic Object Type Annotation
Objects in TypeScript are typed by listing their properties and types:
const person: { name: string; age: number } = { name: "Alice", age: 30 }; // โ Works console.log(person.name); // "Alice" // โ Error! Property 'email' does not exist console.log(person.email);
Optional Properties
Use a question mark (?) to mark a property as optional:
const user: { name: string; email?: string } = { name: "Bob" // email is optional, so it's fine to omit it }; // โ Both work: const user2 = { name: "Charlie", email: "charlie@example.com" }; const user3 = { name: "Diana" }; // No email property
Readonly Properties
Use readonly to prevent a property from being changed after creation:
const config: { readonly apiKey: string; port: number } = { apiKey: "secret123", port: 3000 }; config.port = 4000; // โ Fine, port is mutable config.apiKey = "newsecret"; // โ Error! Cannot assign to readonly property
Nested Objects
Objects can contain other objects:
const company: { name: string; address: { city: string; zipCode: number; } } = { name: "TechCorp", address: { city: "San Francisco", zipCode: 94105 } }; console.log(company.address.city); // "San Francisco"
๐ Arrays
Array Type Syntax
Arrays are typed by specifying the type of their elements. Use either syntax:
Type[]
Most common syntax:
const numbers: number[] = [1, 2, 3]; const names: string[] = ["Alice", "Bob"]; const flags: boolean[] = [true, false];
Array<Type>
Generic syntax (less common):
const numbers: Array<number> = [1, 2, 3]; const names: Array<string> = ["Alice", "Bob"];
Type Safety with Arrays
TypeScript catches type mismatches in arrays:
const scores: number[] = [95, 87, 92]; // โ Works - adding a number scores.push(88); // โ Error! Argument of type 'string' is not assignable to parameter of type 'number' scores.push("100"); // โ IDE knows scores[0] is a number const firstScore = scores[0]; // Type: number
Arrays of Objects
Combine array and object types for realistic data structures:
const users: { name: string; age: number }[] = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }, { name: "Charlie", age: 35 } ]; // โ TypeScript knows users[0] is an object with name and age console.log(users[0].name); // "Alice"
๐ฏ Tuples
Basic Tuple Syntax
const point: [number, number] = [10, 20]; const rgb: [number, number, number] = [255, 128, 0]; const response: [string, number] = ["success", 200]; // โ Error! Type '[number, number, string]' is not assignable to type '[number, number]' const badPoint: [number, number] = [10, 20, "invalid"]; // โ Error! Length mismatch const anotherBad: [number, number] = [10];
Tuples with Optional Elements
Use ? to make tuple elements optional:
const maybe: [string, number?] = ["hello"]; // โ Fine const also: [string, number?] = ["hello", 42]; // โ Also fine
Tuples with Named Elements
For clarity, you can name tuple elements:
const namedTuple: [x: number, y: number] = [5, 10]; const response: [status: string, code: number] = ["OK", 200]; // Names make the code self-documenting: console.log(`Response: ${response.status} (${response.code})`);
Readonly Tuples
Prevent tuple elements from being modified:
const coordinates: readonly [number, number] = [5, 10]; // โ Error! Cannot assign to readonly property coordinates[0] = 20;
๐ Union Types (Preview)
|) to specify multiple options. We'll dive deep into unions later, but you'll encounter them often.
const id: string | number = 42; // โ Can be string or number id = "user-123"; // โ Still valid const values: (string | number)[] = [1, "two", 3]; // Array of mixed types
๐ป Coding Challenges
Challenge 1: Type a Product Object
Create a type annotation for a product object with the following properties:
- name (string)
- price (number)
- inStock (boolean)
- description (string, optional)
Goal: Write the type annotation and create an object that matches it. Test with and without the optional property.
Challenge 2: Type Safety with Arrays
Given an array of student scores, write a function that:
- Takes an array of numbers (scores)
- Returns a number (the average)
- Type annotations required for parameters and return value
Goal: Demonstrate array type safety and function annotations together.
Challenge 3: Tuple for Coordinates
Create a tuple type for a 2D point with (x, y) coordinates. Then create three constants:
- origin at (0, 0)
- pointA at (5, 10)
- pointB at (15, 20)
Goal: Demonstrate tuple creation and fixed-length constraints.
Tuples are great for fixed structures like API responses ([status, data]), coordinates, or return values from destructuring. But for larger objects with multiple properties, use object types (or interfaces โ coming in Chapter 4). Tuples scale poorly with complexity, while objects stay readable as you add properties.
๐ฏ What's Next
Now that you can type objects and arrays, we'll learn Interfaces โ the TypeScript way to define reusable object shapes and create contracts that multiple objects can implement.