keyof constraint
- TypeScript course
- Intermediate
- Lesson 21/89
- 4 min
Learn the property name constraint with keyof.
The keyof constraint
keyof T gives the union of all property names of T. Writing K extends keyof T ensures K is a valid property name of T. So al(obje, "ad") is safe; a non-existent property name is a compile error.
function al<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}
const u = { ad: "Ayşe", yas: 30 };
console.log(al(u, "ad")); // AyşeThe T[K] indexed access type
T[K] gives the value type of property K on T. The signature al<T, K extends keyof T>(o: T, k: K): T[K] ensures the returned value has exactly that property's type. So al(u, "yas") returns number while al(u, "ad") returns string; both are known at compile time.
Practice Fetch a property
Write the generic function al<T, K extends keyof T>(o: T, k: K): T[K] with body return o[k];. Assign { ad: "Ece", yas: 25 } to a variable kisi. Print al(kisi, "ad") and al(kisi, "yas") on separate lines.
Starter code
// al 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
// kisi değişkenine { ad: "Ece", yas: 25 } ata
// kisi'den "ad" ve "yas" özelliklerini ayrı satırlarda yazdırSample solution
function al<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}
const kisi = { ad: "Ece", yas: 25 };
console.log(al(kisi, "ad"));
console.log(al(kisi, "yas"));Expected output
Ece 25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does K extends keyof T guarantee?
function al<T, K extends keyof T>(o: T, k: K): T[K]- That K is a number
- That T is an array
- That T has property K
- That K is a valid property name of T Correct answer
Explanation: keyof T gives all property names of T; K extends keyof T guarantees K is one of those names. It is about K's name, not T's structure.
2 Bound K with keyof
function al<T, K extends ____>(o: T, k: K): T[K] {
return o[k];
}
function al<T, K extends keyof T>(o: T, k: K): T[K] {
return o[k];
}
Explanation: To restrict K to a property name of T you use keyof T. Bare T adds no bound; string accepts any string; keyof K is the wrong direction.
3 keyof constraint parts
| Term | Meaning |
|---|---|
keyof T |
Union of T's property names |
K extends keyof T |
Bounds K to a property name |
T[K] |
Value type of property K |
al(u, "ad") |
Call with a valid property name |