Adding types

INPUT · Slides

Adding types to arrays

01 / 05

An array has a type for its contents

An array is a container that holds several values together. In TypeScript you also write down what goes inside it.

You write it by putting [] after the type of the contents. An array of strings is string[].

const fruit: string[] = ["apple", "orange"];console.log(fruit);

Result

["apple", "orange"]

02 / 05

An array of numbers is number[]

In the same way, an array that only holds numbers is written number[].

Remember that whatever is in front of the [] is the type of the contents.

const scores: number[] = [80, 65, 92];console.log(scores.length);

Result

3

03 / 05

Different kinds cannot get mixed in

Try to put a number into an array you declared as string[] and TypeScript stops you.

JavaScript happily lets you build a mixed array, but that bites you later, when you want to do the same thing to everything in it. Knowing "everything in this array is text" is a relief.

const fruit: string[] = ["apple", 3];

Result

Type error: Type 'number' is not assignable to type 'string'.

04 / 05

What you add gets checked as well

A value you push on also has to match the type you declared.

So you are looked after not only when you build the array, but every time you add to it afterwards.

const names: string[] = ["Yui"];names.push("Haruto");console.log(names);

Result

["Yui", "Haruto"]

05 / 05

Write the type on an empty array too

An array with nothing in it yet is exactly where the type earns its keep.

[] on its own says nothing about what will go in, but write string[] and anything you add later gets checked for you.

const memo: string[] = [];memo.push("milk");console.log(memo);

Result

["milk"]