AI Hints
TypeScript · Lesson 54 of 120

Generic Constraints

Extends.

⏱ 2 min read▶ Video at 42:40🎓 Free
Watch this lesson in the TypeScript courseWatch on YouTube ↗Full TypeScript course

Sometimes T can't be just anything. A function that sorts by price needs items that have a price. A constraint, T extends something, limits what T can be.

Generic Constraints
From the video: Generic Constraints
  • Not just anything
  • Needs a price
  • T extends

Cheapest of anything with a price

T must extend an object with a price. So bikes and helmets both work, and the result keeps its full type. Run it.

app.tstypescript
function cheapest<T extends { price: number }>(items: T[]): T {
  return items.reduce((a, b) => (b.price < a.price ? b : a));
}

const bike = cheapest([{ model: "Trail 500", price: 849.5 }, { model: "City 200", price: 450 }]);
const helmet = cheapest([{ size: "M", price: 40 }, { size: "L", price: 45 }]);

console.log(bike.model, "|", helmet.size);
Output
City 200 | M

Missing a price

These items have no price. Run it. The constraint rejects them.

app.tstypescript
function cheapest<T extends { price: number }>(items: T[]): T {
  return items.reduce((a, b) => (b.price < a.price ? b : a));
}
cheapest([{ model: "Trail 500" }]);
Output
app.ts line 4: Object literal may only specify known properties, and 'model' does not exist in type '{ price: number; }'.

Summary

Constraints say what T must have, while keeping its full type. Next, generic interfaces.

Key takeaways
  • T extends { price }
  • Any matching type
  • Full type kept
Next up: Generic Interfaces — boxes of anything