Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Language

  • English
  • Čeština
  • Deutsch
  • Русский
Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Language

  • English
  • Čeština
  • Deutsch
  • Русский
Sign in

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
undefined

No 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 = [...] gives Type '{ 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.price gives Property 'price' does not exist on type 'Item[]'. The array has no price, only its elements do: item.price.

Instructions

  1. 1

    Give shop the type Item[]. TypeScript then finds the bad element: fix it.

  2. 2

    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 gold
  3. 3

    Write 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 gold
Back

8/10

  1. 1. Object Types
  2. 2. Type Aliases
  3. 3. Missing and Extra Properties
  4. 4. Optional Properties
  5. 5. Read-Only Properties
  6. 6. Interfaces
  7. 7. Nested Objects
  8. 8. Arrays of Objects
  9. 9. Objects in Functions
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.