TypeScript ยท Chapter 7 of 44

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.

Syntax
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.

Example 1 (typescript)
let nums: number[] = [1, 2, 3];
let doubled = nums.map(n => n * 2);
console.log(doubled);
Output
[ 2, 4, 6 ]

TypeScript knows each element is a number, so `n` inside map is typed as number automatically.

Example 2 (typescript)
let names: string[] = ["Ana", "Bo", "Chi"];
names.push("Dee");
console.log(names.join(", "));
Output
Ana, Bo, Chi, Dee

push() 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.
๐Ÿ’ก Note: Use `type[]` for simplicity; `Array<type>` is functionally identical but uses generic syntax.

๐Ÿ“ Quick Quiz

1. How do you declare an array of numbers?

2. What is another valid way to type an array of strings?

3. What happens if you push a number into a string[] array?