AI Hints
Home›Angular Tutorial›Classes, Optional and Union Types and Arrays and Generics
Angular · Lesson 15 of 120

Arrays and Generics

Lists of things.

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

Apps are full of lists. Lists of books, of orders, of users. TypeScript knows what's inside each list.

  • Lists everywhere
  • Books, orders, users
  • Typed lists

Typed arrays

Book, with square brackets, means an array of books. Filter keeps the books under ten pounds. Map turns each book into its title. TypeScript knows the result is an array of strings. Run it. Two titles are cheap enough.

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

const books: Book[] = [
  { title: "Dune", price: 9.99 },
  { title: "Emma", price: 6.99 },
  { title: "Circe", price: 10.99 },
];

const cheap = books.filter(b => b.price < 10);
const titles: string[] = cheap.map(b => b.title);
console.log(titles);
Output
[ 'Dune', 'Emma' ]
Also uses _mode
ts

Generics

Sometimes code works the same way for any type. A generic uses a type parameter, often called T, as a placeholder. You've already seen one. Array of Book is the generic Array type, with Book as its T.

keyvalue
<T>a placeholder type
first<T>(items: T[])works for any type
Array<Book>same as Book[]
In Angularsignal<number>(0)

A generic function

First takes an array of any type T, and returns a T, or undefined, if the array is empty. With strings, T is string. With numbers, T is number. Run it. The title can be upper cased, because it's a string. The price can be rounded, because it's a number. And the empty array gives undefined.

main.tstypescript
function first<T>(items: T[]): T | undefined {
  return items[0];
}

const title = first(["Dune", "Emma"]);
const price = first([9.99, 6.99]);
const nothing = first<number>([]);

console.log(title?.toUpperCase());
console.log(price?.toFixed(1));
console.log(nothing);
Output
DUNE
10.0
undefined
Also uses _mode
ts

Summary

Book array means a list of books, and generics let one function work with any type. Next, decorators.

Key takeaways
  • Book[]
  • filter, map
  • first<T>()
Next up: Decorators — the @ in @Component