CodeBlanks Logo Icon CodeBlanks

typeof narrowing

typeof ile daraltmayı öğrenirsin.

typeof narrowing

typeof operatörü, bir değerin çalışma zamanı türünü dize olarak döndürür. Bir if koşulunda typeof x === "string" gibi bir kontrol, TypeScript'in türlü daraltmasını (narrow) sağlar; koşul içinde x yalnızca string olarak ele alınır. Bu, union türlerde dallanma için en yaygın araçtır.

function format(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();  // string
  }
  return value.toFixed(2);  // number
}

typeof dönüş değerleri

typeof olası değerleri: "string", "number", "bigint", "boolean", "symbol", "undefined", "function", "object". Tarihsel bir tutarsızlık olarak typeof null "object" döner; null değil. Bu yüzden null kontrolü için === null kullanılır.

function len(x: string | null): number {
  if (x === null) return 0;
  return x.length;  // string
}

typeof null;       // "object" (tarihsel)
typeof undefined;  // "undefined"

Uygulama typeof ile birleşim türü işle

format(value: string | number): string fonksiyonunu yaz. Eğer typeof value === "string" ise value.toUpperCase() ile döndür; değilse value.toFixed(2) ile döndür. Sonuçları göstermek için console.log(format("hello")) ve console.log(format(42)) çağrılarını yaz.

Başlangıç kodu

index.ts
// format(value: string | number): string fonksiyonunu typeof ile yaz

// string ise toUpperCase, sayı ise toFixed(2) ile döndür

// format("hello") ve format(42) sonuçlarını yazdır

Örnek çözüm

index.ts
function format(value: string | number): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  return value.toFixed(2);
}

console.log(format("hello"));
console.log(format(42));

Beklenen çıktı

HELLO
42.00

Soru ve cevaplar

Dersin sorularını cevaplarıyla birlikte inceleyebilirsin. Kendini denemek istersen dersi interaktif olarak çöz.

1 typeof x === "number" koşulu bir if bloğu içinde x'i hangi türe daraltır?

  • string
  • "number" (string literal)
  • any
  • number Doğru cevap

Açıklama: typeof x === "number" kontrolü x'i number türüne daraltır; koşul içinde x sayı olarak ele alınır ve sayı yöntemleri kullanılabilir.

2 typeof ile daraltma

Soru
function upper(v: string | number): string {
  if (typeof v === ____) {
    return v.toUpperCase();
  }
  return v.toFixed(0);
}
Cevap
function upper(v: string | number): string {
  if (typeof v === "string") {
    return v.toUpperCase();
  }
  return v.toFixed(0);
}

Açıklama: typeof ile daraltma için değer, olası typeof dizesi olan "string" ile karşılaştırılır; koşul içinde v string olarak ele alınır.

3 typeof narrowing parçaları

Kavram Anlamı
typeof operatörü çalışma zamanı tür dizesi döndürür
"string" string türün typeof değeri
"object" null dahil object türün değeri
if (typeof v === ...) türlü daraltma sağlar

İleri seviye bölümündeki tüm dersler