TypeScript Tutorial menu

TypeScript Arrays and Tuples

TypeScript lets you say what type of items an array holds, and tuples let you describe a list with a fixed length and fixed types.

Typed Arrays

Write the item type followed by []:

Example

typescript
const cities: string[] = ["Karachi", "Lahore", "Quetta"];
const marks: number[] = [78, 91, 66];

cities.push("Multan");   // fine
// marks.push("90");     // Error: Argument of type 'string' is not assignable to parameter of type 'number'

console.log(cities.length, marks[1]);
Output
4 91

There is a second way to write the same thing, Array<number>. Both mean exactly the same:

Example

typescript
const prices: Array<number> = [450, 1200, 80];

Inference With Arrays

If you create an array with values, TypeScript infers its type:

Example

typescript
const fruits = ["Mango", "Apple"];   // string[]
const mixed = [1, "two", 3];         // (string | number)[]

An empty array needs an annotation, or TypeScript cannot know what goes in it:

Example

typescript
const orders: string[] = [];
orders.push("Order #101");

Array Methods Keep Their Types

Methods like map and filter know the types, so the result is typed too:

Example

typescript
const prices: number[] = [1200, 450, 3000];

const labels = prices.map(p => `Rs ${p}`);      // string[]
const cheap = prices.filter(p => p < 1000);    // number[]

console.log(labels);
console.log(cheap);
Output
[ 'Rs 1200', 'Rs 450', 'Rs 3000' ]
[ 450 ]

Readonly Arrays

A readonly array cannot be changed after it is created. This is useful for lists that must stay fixed.

Example

typescript
const weekdays: readonly string[] = ["Mon", "Tue", "Wed", "Thu", "Fri"];

console.log(weekdays[0]);
// weekdays.push("Sat");  // Error: Property 'push' does not exist on type 'readonly string[]'

Tuples

A tuple is an array with a fixed number of items, where each position has its own type.

Example

typescript
let product: [string, number] = ["Ceiling Fan", 8500];

console.log(product[0] + " costs Rs " + product[1]);
// product = [8500, "Ceiling Fan"];  // Error: the order of types is wrong
Output
Ceiling Fan costs Rs 8500
ArrayTuple
LengthAny lengthFixed length
Item typesUsually all the sameEach position has its own type
Example typenumber[][string, number]
Good forLists of similar thingsSmall groups like a pair or a point

Named Tuples and Destructuring

You can give tuple positions names to make them clearer. Destructuring works the same as in JavaScript:

Example

typescript
type Point = [lat: number, lng: number];

const karachi: Point = [24.86, 67.01];
const [lat, lng] = karachi;

console.log(`Latitude ${lat}, Longitude ${lng}`);
Output
Latitude 24.86, Longitude 67.01

Arrays of Objects

You can describe the shape of each object in an array. The next lessons explain object types in detail.

Example

typescript
const students: { name: string; marks: number }[] = [
  { name: "Ali", marks: 82 },
  { name: "Sana", marks: 95 }
];

const best = students.reduce((a, b) => (a.marks > b.marks ? a : b));
console.log(best.name);
Output
Sana

Use a tuple only for short, fixed groups of two or three values. For anything bigger, an object with named properties is easier to read.

Exercise

Exercise

Which type describes an array that holds only numbers?

Learn TypeScript with a teacher

Join the Full Stack Development course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp