Generic constraints
Lesson 5's first<T> worked for any type because its body never touched
the elements - arr[0] needs nothing from T. But most useful generic
functions do need something: a function picking the most recently updated
item must read .updated - and an unconstrained T promises nothing, so
TypeScript refuses the read.
The middle ground between "any type" and "one exact type" is a
constraint:
function newest<T extends { updated: number }>(items: T[]): T {
T extends { updated: number } reads as: T can be anything, as long as it
has a numeric updated. Blog posts, files, user records - all welcome, each
keeping its own full type. The payoff is in the return: callers get back
their complete item type, not some stripped-down { updated: number } -
newest(posts).title works, because T remembered it was a post all along.
Your task: implement newest(items): given a non-empty array of items
that each have a numeric updated timestamp, return the item with the
largest updated.
You'll practice:
- Writing T extends { ... } constraints
- Relying on the constrained capability inside the body while preserving the full type