Summary - keyof and typeof
- TypeScript course
- Intermediate
- Lesson 31/89
- 4 min
Write a safe settings manager with the operators.
Summary - keyof and typeof
keyof gives a type's keys, typeof gives a value's type. Combining them: derive a type from an object with typeof, take its keys with keyof, and write functions that fetch values safely via indexed access. This is ideal for structures like a settings manager.
const ayarlar = { tema: "koyu", dil: "tr" };
type AyarTip = typeof ayarlar;
type AyarAnahtar = keyof AyarTip;
function al(k: AyarAnahtar): AyarTip[AyarAnahtar] {
return ayarlar[k];
}Practice Settings manager
Assign the object { tema: "koyu", dil: "tr" } to a variable ayarlar. Define type AyarTip as typeof ayarlar. Define type AyarAnahtar as keyof AyarTip. Write function al(k: AyarAnahtar): AyarTip[AyarAnahtar] with body return ayarlar[k];. Print the result of al("tema") with console.log.
Starter code
// ayarlar değişkenine { tema: "koyu", dil: "tr" } ata
// AyarTip türünü ayarlar'ın türü olarak tanımla
// AyarAnahtar türünü AyarTip'in anahtarları olarak tanımla
// al fonksiyonu AyarAnahtar parametre alsın
// dönüş türü AyarTip'in AyarAnahtar indeksi olsun
// gövde return ayarlar[k]; olsun
// tema anahtarının değerini al ile getir ve yazdırSample solution
const ayarlar = { tema: "koyu", dil: "tr" };
type AyarTip = typeof ayarlar;
type AyarAnahtar = keyof AyarTip;
function al(k: AyarAnahtar): AyarTip[AyarAnahtar] {
return ayarlar[k];
}
console.log(al("tema"));Expected output
koyu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which order enables safe property access from a settings object?
- indexed access, keyof, typeof
- typeof for type, keyof for keys, indexed access for value Correct answer
- keyof for keys, typeof for type, indexed access
- typeof, indexed access, keyof
Explanation: First typeof derives a type from the object, then keyof takes its keys, and finally indexed access fetches the value safely. Any other order breaks the type-level inference.
2 Indexed access return type
const ayarlar = { tema: "koyu", dil: "tr" };
type AyarTip = typeof ayarlar;
type AyarAnahtar = keyof AyarTip;
function al(k: AyarAnahtar): ____ {
return ayarlar[k];
}
const ayarlar = { tema: "koyu", dil: "tr" };
type AyarTip = typeof ayarlar;
type AyarAnahtar = keyof AyarTip;
function al(k: AyarAnahtar): AyarTip[AyarAnahtar] {
return ayarlar[k];
}
Explanation: Since the return value is ayarlar[k] and k is AyarAnahtar, the return type must be AyarTip[AyarAnahtar]. Just AyarTip or string is too narrow/wide; AyarAnahtar is the key type.
3 Match the operators
| Term | Meaning |
|---|---|
typeof ayarlar |
Derives a type from a value |
keyof AyarTip |
Gives a type's keys |
AyarTip[AyarAnahtar] |
Value type of a key |
al("tema") |
Safe value fetch |