typescript · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
A reply that carries any data. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
interface Reply<T> {
ok: boolean;
data: T;
}
const weather: Reply<string> = { ok: true, data: "sunny" };
const temps: Reply<number[]> = { ok: true, data: [18, 21] };
console.log(weather.data, temps.data[1] - temps.data[0]);
your turn
Your turn. Stock a shelf of shoe sizes.
Fill in the type argument so the second shelf holds numbers, then push a shoe size of your own onto it.
fix it
The checker wants to know what is inside. Fix it!
- Read the error:
TS2314: Generic type 'Parcel<T>' requires 1 type argument(s). Parcelneeds to know what type its contents are. This gift holds a string.- Change
ParceltoParcel<string>on line 2, then press run.
nailed it
your types can wrap any type. :D
- Interfaces can take type parameters, like functions.
- Pass a type argument in angle brackets, like
Parcel<string>. RecordandArrayare generic types too.
new words in your collection
- type argument
This lesson isn’t saved. A free account remembers every lesson you finish.