๐ŸŽ“ A1Learner
๐Ÿ”
0 of 33 lessons completed

TypeScript Arrays

A typed array holds many values of one type in order. Square brackets after a type name name the array type.

An array of numbers

The items and the count both come from the same array.

let scores: number[] = [90, 85, 70];
console.log(scores);
console.log(scores.length);

A string does not fit

push adds one item to the end of an array. A string item breaks the number type.

let scores: number[] = [90, 85];
scores.push("seventy");
console.log(scores);

The generic spelling

Array<number> names the same type as number[]. The angle brackets hold the item type.

let prices: Array<number> = [4, 9, 12];
console.log(prices);

A mixed array

This literal mixes text and a number. The compiler infers a type that accepts both kinds.

let mixed = ["pen", 3];
console.log(mixed);

Example

let scores: number[] = [90, 80, 70];
let total = 0;
for (let i = 0; i < scores.length; i++) {
  total = total + scores[i];
}
console.log(total);
console.log(total / scores.length);

Key points

  • number[] holds an array of numbers.
  • Each item in a typed array must fit the item type.
  • The length property counts the items in an array.
  • Array<number> is the same type in a second spelling.
  • A mixed literal gets an inferred type that accepts both kinds of item.

In this example, the loop visits each score in turn. The total grows by one score on each pass. The total reaches 240 after three passes. The last line divides 240 by 3 and prints 80.

Note

A typed array still grows and shrinks at runtime like a plain JavaScript array.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does the annotation number[] mean?