Arrays of Objects
A shop has many items. An array of objects gets a type like any other array: Item[] is an array whose every element is an Item. It's worth writing, because without it, a mistake in one element can slip through. Here, the rope has a typo:
const shop = [
{ name: "Healing Potion", price: 25 },
{ name: "Rope", prize: 5 },
];
for (const item of shop) {
console.log(item.price);
}This prints:
25
undefinedNo error! TypeScript worked out the array's type from the elements as they are: one has a price, the other a prize. It can't know which spelling is right, so it lets item.price through, as a value that may be undefined. With Item[], you tell it what every element must look like:
type Item = { name: string; price: number };
const shop: Item[] = [
{ name: "Healing Potion", price: 25 },
{ name: "Rope", prize: 5 },
{ name: "Lamp", price: "12" },
];main.ts(5,21): error TS2561: Object literal may only specify known properties, but 'prize' does not exist in type 'Item'. Did you mean to write 'price'?
main.ts(6,21): error TS2322: Type 'string' is not assignable to type 'number'.Each error points at the element with the problem, by its line and column.
In a for...of loop over an Item[], every item is an Item, so TypeScript knows that item.price is a number. You can add it up without worrying, and a typo such as item.prices is reported: Property 'prices' does not exist on type 'Item'. Did you mean 'price'? push checks a new element too: shop.push({ name: "Map" }) gives Property 'price' is missing in type '{ name: string; }' but required in type 'Item'.
And an array that starts empty and gets its elements later needs the type, as you know from lesson 2: const cart: Item[] = [];.
Typical mistakes:
- Forgetting the
[].const shop: Item = [...]givesType '{ name: string; price: number; }[]' is missing the following properties from type 'Item': name, price. In other words: an array of items isn't an item. - The array instead of the element in the loop.
total += shop.pricegivesProperty 'price' does not exist on type 'Item[]'.The array has no price, only its elements do:item.price.
Instructions
Give shop the type Item[]. TypeScript then finds the bad element: fix it.
With a for...of loop, print every item like this:
Healing Potion: 25 gold
Mana Potion: 30 gold
Antidote: 15 gold
Elixir of Strength: 60 goldWrite a function totalPrice with a parameter items of type Item[] and the return type number, which returns the sum of the prices. Print the line below, using totalPrice(shop):
Total: 130 goldStart programming for free
8/10