Working with Collections
When building applications, we often need to work with collections of data. TypeScript provides two main ways to handle this: Arrays and Objects.
Arrays: Ordered Lists
Arrays are like a line of items, where each item has its position. Think of them as a shopping list or a playlist.
// An array of numbers (like scores in a game)
let scores: number[] = [85, 92, 78, 95];
// An array of strings (like a list of player names)
let players: string[] = ["Alex", "Sam", "Taylor"];
You can also write arrays using a different syntax:
let scores: Array<number> = [85, 92, 78, 95];
Objects: Related Data
Objects help us group related information together. They're perfect for representing things with multiple properties.
// Describing a player in a game
type Player = {
name: string;
score: number;
isActive: boolean;
}
let player1: Player = {
name: "Alex",
score: 85,
isActive: true
};
Combining Arrays and Objects
Often, you'll work with arrays of objects. This is very common in real applications:
let players: Player[] = [
{ name: "Alex", score: 85, isActive: true },
{ name: "Sam", score: 92, isActive: false },
{ name: "Taylor", score: 78, isActive: true }
];
Best Practices
- Always define object shapes using interfaces or types
- Use consistent naming conventions
- Consider making properties optional when appropriate:
type Player = {
name: string;
score: number;
isActive: boolean;
lastLogin?: Date; // Optional property
}
Practice Exercise
Try creating an array of objects representing your favorite books. Include properties like title, author, and year published.