×

typescript · level 2 · unit 1 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Objects travel through functions and line up in arrays.

Functions can take objects as parameters and hand objects back. Label them with your interface, like function describe(pet: Pet): string, and read properties inside as usual.

An array of objects uses the shape and square brackets: Pet[]. A for...of loop then hands you one whole object per lap.

Objects can also be , one inside another. An owner might have a pet property that is itself a Pet. Reach inside with two dots: owner.pet.name.

interface Pet { name: string; age: number }
function describe(pet: Pet): string {
  return `${pet.name} (${pet.age})`;
}
const pets: Pet[] = [{ name: "Rex", age: 3 }, { name: "Tom", age: 7 }];
for (const pet of pets) {
  console.log(describe(pet));
}
const owner = { name: "Sam", pet: pets[0] };
console.log(owner.pet.name);

A short interface can sit on one line, like interface Pet { name: string; age: number }.