TypeScript Arrays
Arrays in TypeScript can be typed so that every element must be the same type. You write the element type followed by square brackets, such as `number[]` for an array of numbers.
Typed arrays help prevent bugs like accidentally mixing strings and numbers in a list that should hold only one kind of value, and they also give you accurate autocomplete for array methods.
let nums: number[] = [1, 2, 3];
let names: Array<string> = ["Ana", "Bo"];Declaring typed arrays
You can write `let nums: number[] = [1, 2, 3];` or the equivalent generic form `let nums: Array<number> = [1, 2, 3];`. Both mean the same thing.
Working with array methods
Because TypeScript knows the element type, methods like `.map()` and `.filter()` give you correctly typed results and catch mistakes such as calling a string method on a number.
let nums: number[] = [1, 2, 3];
let doubled = nums.map(n => n * 2);
console.log(doubled);[ 2, 4, 6 ]TypeScript knows each element is a number, so `n` inside map is typed as number automatically.
let names: string[] = ["Ana", "Bo", "Chi"];
names.push("Dee");
console.log(names.join(", "));Ana, Bo, Chi, Deepush() only accepts strings because the array is typed as string[].
Key points
- Typed arrays use `type[]` or `Array<type>` syntax.
- All elements in a typed array must match the declared type.
- Array methods like map and filter respect the element type.
- Adding a value of the wrong type causes a compile-time error.
