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.lengthlegal insidelongest K extends keyof Trejects keys the objects do not haveT[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.


