📘
Arrays and Objects in TypeScript
Beginner
80 XP
30 min
Lesson Content
Arrays and Objects in TypeScript
TypeScript provides strong typing for arrays and objects, essential for React state and Vue data.
Typed Arrays
let numbers: number[] = [1, 2, 3];
let names: Array = ["Alice", "Bob"];
// Array methods with types
numbers.map((n: number) => n * 2); Object Types
let user: { name: string; age: number } = {
name: "John",
age: 30
};Array of Objects
interface User {
id: number;
name: string;
}
let users: User[] = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];Readonly Arrays
let readonlyNumbers: ReadonlyArray = [1, 2, 3];
// readonlyNumbers.push(4); // Error! Example Code
Work with typed arrays and objects
interface Product {
id: number;
name: string;
price: number;
}
const products: Product[] = [
{ id: 1, name: "Laptop", price: 999 },
{ id: 2, name: "Mouse", price: 25 }
];
const total = products.reduce((sum, p) => sum + p.price, 0);
console.log(`Total: $${total}`);Expected Output:
Total: $1024
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code