typescript · level 2 · unit 1 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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 }.
guess first
Two dots deep. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Address { town: string; postcode: string }
interface Shop { name: string; address: Address }
const shop: Shop = {
name: "Bean There",
address: { town: "Bath", postcode: "BA1 1AA" },
};
shop.address.town = "Bristol";
console.log(`${shop.name}, ${shop.address.town}`);
your turn
Your turn. Add up a shopping basket.
Push two more items into the basket, each with a name and a price. Then finish the loop so it adds each item's price to the total.
fix it
The town is hiding one level down. Fix it!
- Read the error:
TS2339: Property 'town' does not exist on type 'Friend'. - A friend has a name and a home. The town is inside the nested home object.
- Change
friend.towntofriend.home.townon line 7, then press run.
nailed it
your objects work as a team. :D
- Label parameters and return types with your own interfaces.
Pet[]is an array where every item is aPet.- Reach into nested objects with more dots, like
owner.pet.name.
new words in your collection
- nested
This lesson isn’t saved. A free account remembers every lesson you finish.