typescript · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A tells a generic what it can count on.
A generic like <T> works with any type. That is powerful, but it means TypeScript knows nothing about T. Ask for item.name and the checker stops you with TS2339, because not every type has a name.
A constraint fixes that. Write <T extends { name: string }> and T can be any type, so long as it has a name that is a string. Inside the function you may use .name, and callers still get their own full type back, extra properties and all.
Pass something without a name and the checker refuses it with TS2345.
function longestName<T extends { name: string }>(items: T[]): T {
let best: T = items[0];
for (const item of items) {
if (item.name.length > best.name.length) {
best = item;
}
}
return best;
}
const pets = [{ name: "Rex", legs: 4 }, { name: "Tibbles", legs: 4 }];
const winner = longestName(pets);
console.log(winner.name, winner.legs); Read extends in a constraint as “must at least have”.
guess first
One price tag, two items. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
function priceTag<T extends { price: number }>(item: T): string {
return `Only £${item.price}!`;
}
const tea = { name: "Tea", price: 3 };
const cake = { name: "Cake" };
console.log(priceTag(tea));
console.log(priceTag(cake));
your turn
Your turn. Find the oldest in the family.
Fill in the constraint so oldest may read .age, then show the oldest person's name.
fix it
The snack total will not add up. Fix it.
- Read the error:
TS2339sayspricedoes not exist on typeT. Tcould be any type at all, so the checker cannot promise aprice. GiveTa constraint.- Change line 1 to
function total<T extends { price: number }>(items: T[]): number {, then run.
nailed it
your generics know what they can count on. :D
<T extends { name: string }>lets the function read.name.- Callers still get their full type back, not the constraint.
TS2339inside a generic often means a constraint is missing.
new words in your collection
- constraint
This lesson isn’t saved. A free account remembers every lesson you finish.