Describe the shape of an object

INPUT · Slides

Arrays of objects

01 / 06

Name a shape and you can put [] on it

A register, a product list — real data is nearly always "objects of the same shape, lined up".

You write it just like the arrays in chapter 1: [] after the type of the contents. Item[] means "an array that only holds things shaped like Item".

interface Item {  name: string;  price: number;}const list: Item[] = [  { name: "apple", price: 120 },  { name: "orange", price: 80 },];console.log(list.length);

Result

2

02 / 06

Showing the whole thing

Show the array as it is and the objects inside come out with it.

It is { ... } items lined up inside [ and ]. With much in there the line gets long, so it reads better to pull out just the part you want to check.

interface Fruit {  name: string;  count: number;}const basket: Fruit[] = [  { name: "apple", count: 2 },];console.log(basket);

Result

[{ name: "apple", count: 2 }]

03 / 06

Take them out one at a time with for...of

To handle them one at a time, use for...of. This is the part that feels good.

The i you take out is understood to be an Item without you writing it. So a typo in i.name gets caught on the spot too.

interface Item {  name: string;  price: number;}const list: Item[] = [  { name: "pen", price: 120 },  { name: "notebook", price: 200 },];for (const i of list) {  console.log(i.name);}

Result

pen
notebook

04 / 06

Work out a total

Since the type of what you take out is known, it goes straight into a sum.

i.price is declared as a number, so + is guaranteed to be addition. Had a string been mixed in, this is where things would have stuck together instead.

interface Item {  name: string;  price: number;}const list: Item[] = [  { name: "pen", price: 120 },  { name: "notebook", price: 200 },];let total: number = 0;for (const i of list) {  total = total + i.price;}console.log(total);

Result

320

05 / 06

What you push gets checked too

Starting from an empty array and adding with push works just as before.

The shape of what you add gets checked, so nothing that disagrees with the declaration can creep in later.

interface Todo {  task: string;  done: boolean;}const list: Todo[] = [];list.push({ task: "cleaning", done: false });console.log(list.length);

Result

1

06 / 06

Incomplete ones cannot line up

Write an object in the array with part of the shape missing and it is an error. The accident of "I forgot one property on one row" stops happening.

You can now leave the shape of your data written in the code. A type is a blueprint for data. Let us write some.

interface Item {  name: string;  price: number;}const list: Item[] = [  { name: "sweet" },];

Result

Type error: Property 'price' is missing in type '{ name: string; }' but required in type 'Item'.