Lesson 2 of 10

Generic constraints

Goal

Require only what you need

01

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.

02

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
  1. No type errors
  2. Finds the item by its id
  3. Returns undefined when nothing matches
  4. The result keeps every field of the item
  5. An item without an id is rejected
03

Hints

0/3
main.ts
OutputTypeScript 5.9

Loading the TypeScript compiler. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.