Arrays with Types

A list where everything belongs

7 min read

Typing a whole list at once

Real websites are full of lists: products, comments, tags, scores. In TypeScript you describe what a whole array holds by writing the element type followed by square brackets:

let tags: string[] = ['sale', 'new', 'popular'];
let scores: number[] = [88, 92, 79];
let answers: boolean[] = [true, false, true];

Read string[] as an array of strings. Once declared, the array only accepts that kind of element:

tags.push('featured');
tags.push(42);

The first push is fine. The second gets an error, because 42 is not a string. This protects you from the sneaky bug where one odd value hides inside a list of hundreds and only explodes much later.

TypeScript knows what comes out, too

Because the element type is known, everything you read from the array is typed as well. That makes array methods much safer and gives you great autocomplete:

let scores: number[] = [88, 92, 79];

const doubled = scores.map((s) => s * 2);
const top = scores.filter((s) => s > 85);

Inside map and filter, TypeScript already knows s is a number, so s * 2 and s > 85 are checked without you writing a single extra annotation. If you tried s.toUpperCase() in there, TypeScript would object, because numbers do not have that method.

An alternative spelling

You will sometimes see the same type written another way:

let tags: Array<string> = ['sale', 'new'];

Array<string> means exactly the same thing as string[]. Most codebases prefer the shorter string[] form, but it is worth recognizing both. The angle-bracket style is a small preview of generics, which we will meet properly near the end of the course.

Empty arrays need a hint. If you write let items = []; TypeScript cannot guess what will go inside. Give it an annotation, like let items: string[] = [];, so every later push is checked against the right type.

Quick check

Q1 How do you declare an array that may only contain numbers?

Want to save your progress? It's free.

Create a free account