Typed Arrays

Two Ways to Write an Array Type

number[] and Array<number> mean the same thing: an array where every element is a number. Most code uses the short T[] form.

Example

const prices: number[] = [499, 1299, 89];
const categories: Array<string> = ["Electronics", "Books"];

prices.push(250);
categories.push("Toys");

const total = prices.reduce((sum, p) => sum + p, 0);
console.log(prices, "total:", total);
console.log(categories.map((c) => c.toUpperCase()));

Output

[ 499, 1299, 89, 250 ] total: 2137
[ 'ELECTRONICS', 'BOOKS', 'TOYS' ]

Wrong Element Type

Example

Pushing a string into a number[] is caught (TS2345).

const prices: number[] = [499, 1299];
prices.push("free");

Compiler output (tsc)

Line 2: error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

Arrays of Mixed Types and Objects

Example

Use a union for mixed arrays and an object type for arrays of records.

const ids: (number | string)[] = [101, "SKU-202", 303];

type Product = { name: string; price: number };
const cart: Product[] = [
  { name: "Notebook", price: 60 },
  { name: "Pen", price: 20 },
];

console.log(ids.length, "ids");
for (const item of cart) {
  console.log(item.name.padEnd(10), item.price);
}

Output

3 ids
Notebook   60
Pen        20