Arrays, tuples and read-only collections
You already know typed arrays like number[]. Today we go further: arrays of objects, tuples for fixed-length lists, read-only collections and how to describe objects with dynamic keys. With these pieces you can model almost any data structure found in a common application, from task lists to coordinate pairs or configuration dictionaries.
Arrays of objects
Combining an object type with brackets gives an array of those objects: Task[]. Array methods preserve types, so filter returns Task[] and map returns whatever type your function produces. A delicate situation with strict: find returns Task | undefined, because there may be no element meeting the condition, and you must handle that case before using the result.
interface Task {
id: number;
title: string;
done: boolean;
}
const tasks: Task[] = [
{ id: 1, title: 'Learn types', done: true },
{ id: 2, title: 'Practice', done: false },
];
const pending = tasks.filter((t) => !t.done); // Task[]
const titles = tasks.map((t) => t.title); // string[]
const found = tasks.find((t) => t.id === 2); // Task | undefined
if (found) {
console.log(found.title.toUpperCase());
}
console.log(pending.length, titles);Tuples
A tuple is an array with a fixed length and a concrete type at each position. It is written with brackets containing the types in order: [number, number] for coordinates, [string, number] for a name and age pair. They are ideal for returning several values from a function, as useState does in React. You can label the elements to document them, like [lat: number, lng: number]. Without a tuple, an array [string, number] would be inferred as (string | number)[], and you would lose the position information.
type Point = [x: number, y: number];
function minMax(values: number[]): [min: number, max: number] {
return [Math.min(...values), Math.max(...values)];
}
const origin: Point = [0, 0];
const [min, max] = minMax([4, 9, 2]); // destructuring keeps the types
// const wrong: Point = [1, 2, 3]; // error: Source has 3 element(s) but target allows only 2
console.log(origin, min, max);Read-only and dynamic keys
With readonly before an array type, or with ReadonlyArray, the compiler forbids push, pop, assigning by index and other methods that mutate. It is very useful on parameters: it declares that your function will not alter the list it receives. For dictionaries where the keys are not known in advance, there is the index signature: { [key: string]: number } says that any text key has a numeric value. Under standard strict, reading a key that does not exist returns number according to the type, even though at runtime it is undefined; the Record<string, number> type, which we will see in week 7, is a shorter way to write it.
function total(prices: readonly number[]): number {
// prices.push(1); // error: Property 'push' does not exist on type 'readonly number[]'
return prices.reduce((sum, p) => sum + p, 0);
}
const stock: { [product: string]: number } = {
apple: 10,
pear: 4,
};
stock.banana = 25;
const frozen = ['a', 'b'] as const; // readonly ['a', 'b']
console.log(total([1, 2, 3]), stock, frozen);When you doubt between an array and a tuple, ask yourself one question: does each position mean something different? If the answer is yes, as in a name and age pair, use a tuple; but if you have more than three elements, an object with named properties is almost always more readable. It is also worth remembering that readonly on an array is shallow: it prevents changing the list, but the objects inside remain modifiable. To protect them, mark their properties as readonly too. These small decisions prevent mutation bugs that are hard to trace in large programs.
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف