Skip to content
dreamcode
dreamcode
Map
Constraints
Lesson 14 of 26
+15 XP on finish
TS ADVANCEDChapter 3 · TS Advanced

Generic Constraints

A plain <T> accepts any type, which means you cannot use any of its properties. Add a constraint with extends to require a shape: <T extends { length: number }> accepts strings, arrays and anything else with a length. <K extends keyof T> limits a key to the real keys of T, which is how you write a type-safe property getter.

Worked example

How it reads

  • The constraint is what makes a.length legal inside longest
  • K extends keyof T rejects keys the objects do not have
  • T[K][] is "an array of whatever type that property has"
Cloud tip: Start generic functions unconstrained, then add exactly the constraint the body needs and no more.
index.ts
TYPESCRIPT
type-checked, then run in your browser
Console
Run your code to see its output here.
YOUR TURN

Constrain T to objects with an id: number, and make firstWithId return just the first item's id. Log it: 7.

Press Run to check your work.