AI Hints
Home›Angular Tutorial›Decorators, import and export and Practice: Typed Books
Angular · Lesson 18 of 120

Practice: Typed Books

Your turn.

⏱ 2 min read▶ Video at 21:50🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Let's practise TypeScript. You'll describe books with an interface, and write a typed function.

  • An interface
  • A typed function
  • Your turn

Cheap books

Your turn. Pause the video, and try this. Write a Book interface, with a title, an author, and a price. Make an array of three books. Then write a function, that returns the books cheaper than a maximum price. Here is one solution. Book array keeps the list typed. And cheaper than filters by price. Two books cost less than eight pounds.

✍️ Exercise: Cheap books

Write interface Book (title, author, price), an array of 3 books, and cheaperThan(list, max): Book[]. Print the books under £8.

Show hint

list.filter(b => b.price < max)

Show solution
main.tstypescript
interface Book {
  title: string;
  author: string;
  price: number;
}

const books: Book[] = [
  { title: "Dune", author: "Frank Herbert", price: 9.99 },
  { title: "Emma", author: "Jane Austen", price: 6.99 },
  { title: "Persuasion", author: "Jane Austen", price: 7.49 },
];

function cheaperThan(list: Book[], max: number): Book[] {
  return list.filter(b => b.price < max);
}

cheaperThan(books, 8).forEach(b => console.log(`${b.title} by ${b.author}`));
Output
Emma by Jane Austen
Persuasion by Jane Austen

What module two taught

Types catch mistakes before running. Interfaces describe objects. Classes, unions, and generics describe everything else. And decorators, and imports, are at the top of every Angular file.

keyvalue
Typesstring, number, boolean
Shapesinterface, type
Classesprivate, constructor
Every file@decorators, imports

Summary

You know enough TypeScript to write Angular. That's the end of module two. Next, components, and templates.

Key takeaways
  • Interfaces
  • Typed functions
  • Ready for Angular
Next up: Components — the building blocks