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
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]);4 91
There is a second way to write the same thing, Array<number>. Both mean exactly the same:
Example
const prices: Array<number> = [450, 1200, 80];Inference With Arrays
If you create an array with values, TypeScript infers its type:
Example
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
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
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);[ '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
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
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 wrongCeiling Fan costs Rs 8500
| Array | Tuple | |
|---|---|---|
| Length | Any length | Fixed length |
| Item types | Usually all the same | Each position has its own type |
| Example type | number[] | [string, number] |
| Good for | Lists of similar things | Small 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
type Point = [lat: number, lng: number];
const karachi: Point = [24.86, 67.01];
const [lat, lng] = karachi;
console.log(`Latitude ${lat}, Longitude ${lng}`);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
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);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?
