Summary - Generic constraints
- TypeScript course
- Intermediate
- Lesson 23/89
- 4 min
Write a property picker with constrained generics.
Summary - Generic constraints
Generic constraints limit what a type parameter can do. T extends Adli forces specific properties; K extends keyof T makes property names safe; <T = string> gives the type parameter a default. Combining the three you can write type-safe property selectors and helpers.
function sec<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}Practice Type-safe property selector
Write the generic function sec<T, K extends keyof T>(o: T, k: K): T[K] with body return o[k];. Assign { kullanici: "ali", puan: 90 } to a variable kayit. Print sec(kayit, "kullanici") and sec(kayit, "puan") on separate lines.
Starter code
// sec fonksiyonunu iki tür parametreli generic olarak yaz
// K parametresini T'nin özellik adlarıyla sınırla
// dönüş türü T'nin K özelliği olsun
// gövde return o[k]; olsun
// kayit değişkenine { kullanici: "ali", puan: 90 } ata
// kayit'tan "kullanici" ve "puan" özelliklerini ayrı satırlarda yazdırSample solution
function sec<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}
const kayit = { kullanici: "ali", puan: 90 };
console.log(sec(kayit, "kullanici"));
console.log(sec(kayit, "puan"));Expected output
ali 90
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 You want to access x.uzunluk in a generic function body. Which constraint is needed?
- T extends Uzunluklu, Uzunluklu = { uzunluk: number } Correct answer
- K extends keyof T
- T = string
- None; no constraint is needed
Explanation: To access a property the type must have it; you declare this with extends. keyof bounds a property name, default only gives a fallback type; neither grants access.
2 Property selector signature
function sec<T, K extends ____>(o: T, k: K): T[K] {
return o[k];
}
function sec<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}
Explanation: To bound K to a property name of T you use keyof T. Bare T adds no bound; string accepts any name; keyof K is the wrong direction.
3 Match constraint kinds
| Term | Meaning |
|---|---|
T extends Adli |
Forces a specific property |
K extends keyof T |
Bounds a property name |
<T = string> |
Gives a default type |
T[K] |
Value type of property K |