Lesson 2 of 10
Generic constraints
- 12 min
- 5 checks
- 3 hints
- Go to task
Goal
Require only what you need
Explanation
A type parameter with no constraint accepts any type, and that's exactly why it lets you do almost nothing with it. Inside findById<T>, item.id is a type error, because T could be a number or a string with no id.
A constraint spells out what the function accepts. function longest<T extends { length: number }>(a: T, b: T): T accepts strings, arrays and anything else with a length, rejects numbers, and lets you use a.length inside.
The common mistake is to drop the type parameter and write items: { id: number }[]. That accepts the books, but the result becomes just { id: number }, so book.title turns into an error. A constraint requires id and keeps the rest of the fields with it.
Your task
Put a constraint on T in findById that requires every item to have a numeric id, while the result stays T | undefined with all of its fields.
Checks
5 checks- No type errors
- Finds the item by its id
- Returns undefined when nothing matches
- The result keeps every field of the item
- An item without an id is rejected