CodeBlanks Logo Icon CodeBlanks

Indexing with keyof

Learn safe property access with keyof.

Indexing with keyof

The type obtained with keyof can be used for indexed access in square brackets. Kisi[keyof Kisi] gives the union of all property value types of Kisi. This enables safe property access on an object; a wrong key is a compile error.

interface Kisi {
  ad: string;
  yas: number;
}
type DegerTuru = Kisi[keyof Kisi];
// string | number

Safe property access

If a function takes a k: keyof Kisi parameter, the o[k] access in the body is type-safe. The compiler knows k is a valid property name. With return type Kisi[keyof Kisi], the union of all possible value types is returned.

Practice Fetch a value by key

Define interface Kisi with ad: string and yas: number. Write function al(o: Kisi, k: keyof Kisi): Kisi[keyof Kisi] with body return o[k];. Assign { ad: "Ela", yas: 28 } to a variable kisi. Print the result of al(kisi, "ad") with console.log.

Starter code

index.ts
// Kisi arayüzünü ad ve yas ile tanımla
// al fonksiyonu yaz: o Kisi, k Kisi'nin özellik adlarından biri
// dönüş türü tüm değer türlerinin birleşimi olsun
// gövde return o[k]; olsun
// kisi değişkenine { ad: "Ela", yas: 28 } ata
// kisi'den ad değerini al fonksiyonuyla getir ve yazdır

Sample solution

index.ts
interface Kisi {
  ad: string;
  yas: number;
}
function al(o: Kisi, k: keyof Kisi): Kisi[keyof Kisi] {
  return o[k];
}
const kisi = { ad: "Ela", yas: 28 };
console.log(al(kisi, "ad"));

Expected output

Ela

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does T become in the code below?

index.ts
interface Kisi { ad: string; yas: number; }
type T = Kisi[keyof Kisi];
  • "ad" | "yas"
  • Kisi
  • any
  • string | number Correct answer

Explanation: Kisi[keyof Kisi] gives the union of all property value types. Kisi's properties are string and number, so the result is string | number. It does not give the key names.

2 Indexed access type

Question
interface Kisi { ad: string; yas: number; }
function al(o: Kisi, k: keyof Kisi): Kisi[____] {
  return o[k];
}
Answer
interface Kisi { ad: string; yas: number; }
function al(o: Kisi, k: keyof Kisi): Kisi[keyof Kisi] {
  return o[k];
}

Explanation: To get all value types you write keyof Kisi in the brackets. string is just one type; Kisi is the wrong type; ad is a single property name.

3 keyof indexing parts

Term Meaning
keyof Kisi Kisi's property names
Kisi[keyof Kisi] Union of all value types
o[k] Safe property access
al(kisi, "ad") Fetch a value by key

All lessons in Intermediate