A

Arrays

TypeScript arrays are typed collections with powerful methods for transformation and iteration.

Code

typescript
1// Typed arrays
2const numbers: number[] = [1, 2, 3, 4, 5];
3const names: string[] = ["Alice", "Bob", "Charlie"];
4
5// Alternative syntax with Array generic
6const scores: Array<number> = [95, 87, 92, 88];
7
8// Array methods with type inference
9const doubled = numbers.map((n) => n * 2);
10const evens = numbers.filter((n) => n % 2 === 0);
11const sum = numbers.reduce((acc, n) => acc + n, 0);
12
13// Finding elements
14const found = names.find((name) => name.startsWith("A"));
15const index = names.findIndex((name) => name === "Bob");
16
17// Checking conditions
18const hasNegative = numbers.some((n) => n < 0);
19const allPositive = numbers.every((n) => n > 0);
20
21// Tuple types (fixed-length arrays with specific types)
22const coordinate: [number, number] = [10, 20];
23const userRecord: [number, string, boolean] = [1, "Alice", true];
24
25// Destructuring
26const [x, y] = coordinate;
27const [id, username, isActive] = userRecord;
28
29// Spread operator
30const moreNumbers = [...numbers, 6, 7, 8];
31const allNames = [...names, "David"];
32
33console.log(`Doubled: ${doubled}`);
34console.log(`Sum: ${sum}`);
35console.log(`Found: ${found}`);
36console.log(`Coordinate: (${x}, ${y})`);

Run this example locally

$ npx ts-node basics/arrays.ts