keyof operator
- TypeScript course
- Intermediate
- Lesson 28/89
- 4 min
Learn the keys of a type with keyof.
The keyof operator
The keyof operator gives the union of all property names of a type. When you write keyof Ayar, each property name of Ayar becomes a string literal type in a union. The result is a type, not a value; it can only appear in type positions.
interface Ayar {
tema: string;
dil: string;
}
type Anahtar = keyof Ayar;
// "tema" | "dil"Type alias from keyof
The union produced by keyof can be stored as a type alias and used as a parameter type. The function then accepts only valid property names; a wrong name is a compile error. This is useful for functions that accept setting or configuration keys.
Practice Print with a key type
Define interface Ayar with tema: string and dil: string. Define type Anahtarlar as keyof Ayar. Write function yaz(a: Anahtarlar): void that prints the key via console.log(a). Call yaz("tema").
Starter code
// Ayar arayüzünü tema ve dil özellikleriyle tanımla
// Anahtarlar türünü Ayar'ın özellik adları olarak tanımla
// yaz fonksiyonu Anahtarlar parametre alsın
// gövdede console.log ile parametreyi yazdır
// tema anahtarıyla çağırSample solution
interface Ayar {
tema: string;
dil: string;
}
type Anahtarlar = keyof Ayar;
function yaz(a: Anahtarlar): void {
console.log(a);
}
yaz("tema");Expected output
tema
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the Anahtarlar type become below?
interface Ayar { tema: string; dil: string; }
type Anahtarlar = keyof Ayar;- string | number
- { tema: string; dil: string }
- string
- The union "tema" | "dil" Correct answer
Explanation: keyof gives a union of property name literals. Since Ayar's properties are tema and dil, the result is "tema" | "dil". It does not give value types or the object itself.
2 Add keyof
interface Ayar { tema: string; dil: string; }
type Anahtar = ____ Ayar;
interface Ayar { tema: string; dil: string; }
type Anahtar = keyof Ayar;
Explanation: To get a type's property names you use keyof. typeof derives a type from a value; Pick and Partial serve other purposes.
3 keyof parts
| Term | Meaning |
|---|---|
keyof Ayar |
Union of Ayar's property names |
type Anahtarlar = keyof Ayar |
Type alias of key names |
function yaz(a: Anahtarlar) |
Key-type parameter |
yaz("tema") |
Call with a valid key |