TypeScript
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.
Örnek çözümü göster
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));
Kendini test et
-
typeof x === "number" koşulu bir if bloğu içinde x'i hangi türe daraltır?
- string
- "number" (string literal)
- any
- number
Cevabı göster
number — 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.
-
typeof ile daraltma
function upper(v: string | number): string {
if (typeof v === ____) {
return v.toUpperCase();
}
return v.toFixed(0);
}
Cevabı göster
function upper(v: string | number): string {
if (typeof v === "string") {
return v.toUpperCase();
}
return v.toFixed(0);
}
-
typeof narrowing parçaları
- 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
Sıradaki ders: in operatörü