๐Ÿ  Object Types

TypeScript Fundamentals โ€” Objects, Arrays & Tuples
TypeScript Fundamentals
Course 1 ยท Chapter 3 ยท Objects, Arrays & Tuples

๐Ÿ“ฆ Objects, Arrays & Tuples

Primitives are the building blocks, but real programs work with collections: objects holding multiple properties, arrays of values, and tuples with fixed structures. This chapter teaches you to type these complex data structures with precision.

๐Ÿ  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

A tuple is an array with a fixed length and specific types at each position. Unlike regular arrays, tuples enforce the exact structure.

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)

Sometimes a value can be one of several types. Use the pipe operator (|) 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.

โ†’ Solution

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.

โ†’ Solution

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.

โ†’ Solution

๐Ÿ’ก Real-World Tip: Know When to Use Tuples

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.