Generic Constraints
Question
What does "T extends SomeType" do in a generic?
Hint
Constraints allow accessing properties of T within the generic.
Explanation
"T extends SomeType" constrains the type parameter T to be assignable to SomeType. This allows accessing properties of SomeType on values of type T. Example: function getProp<T extends { name: string }>(obj: T) { return obj.name; }. The constraint ensures obj always has a name property. The keyof operator is often used with constraints: function getProp<T, K extends keyof T>(obj: T, key: K) { return obj[key]; }. Constraints can reference other type parameters: function merge<T extends U, U>(a: T, b: U).
Related Resources
Related Lessons
- Generics
Learn generics.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.