๐ Object Types
๐ฆ Objects, Arrays & Tuples
๐ Object Types
Basic Object Type Annotation
Objects in TypeScript are typed by listing their properties and types:
Optional Properties
Use a question mark (?) to mark a property as optional:
Readonly Properties
Use readonly to prevent a property from being changed after creation:
Nested Objects
Objects can contain other objects:
๐ Arrays
Array Type Syntax
Arrays are typed by specifying the type of their elements. Use either syntax:
Type[]
Most common syntax:
Array<Type>
Generic syntax (less common):
Type Safety with Arrays
TypeScript catches type mismatches in arrays:
Arrays of Objects
Combine array and object types for realistic data structures:
๐ฏ Tuples
Basic Tuple Syntax
Tuples with Optional Elements
Use ? to make tuple elements optional:
Tuples with Named Elements
For clarity, you can name tuple elements:
Readonly Tuples
Prevent tuple elements from being modified:
๐ Union Types (Preview)
|) to specify multiple options. We'll dive deep into unions later, but you'll encounter them often.
๐ป 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.