×

typescript · level 2 · unit 5 · lesson 2

  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

Interfaces can take a type parameter too.

A parcel can hold anything, but you want to know what is inside. Give an interface a type parameter: interface Parcel<T> { label: string; contents: T }. Each use passes a in angle brackets, like Parcel<string> or Parcel<number[]>.

You have used these already. Record<string, number> is a generic type with two type arguments. Even string[] has a longer name: Array<string>.

Generic types suit wrappers that look the same outside but carry different things, like a server reply that always has ok but different data.

interface Parcel<T> {
  label: string;
  contents: T;
}
const book: Parcel<string> = { label: "Book", contents: "Matilda" };
const dice: Parcel<number[]> = { label: "Dice", contents: [3, 5] };
const names: Array<string> = ["Zoe", "Max"];
console.log(book.contents.toUpperCase());
console.log(dice.contents.length, names.length);

With a generic type you usually write the type argument yourself, because there is no call to work it out from.