typeof guard — primitive turlarni tekshirish

~15 daq · TypeScript · Type Narrowing

Union tur bilan ishlayapsiz — parametr string | number. string metodlari ishlatmoqchisiz, lekin TypeScript ruxsat bermaydi:

function hisoblash(a: number | string): number {
  return a * 2;
  // ❌ Operator '*' cannot be applied to 'string | number'
}

TypeScript ikkalasida ham mavjud operatsiyalargagina ruxsat beradi. Faqat bir turda bor narsaga yetishish uchun — type narrowing: if bloki ichida turni aniqlash.


typeof guard

typeof JavaScript operatori — TypeScript buni narrowing uchun tushunadi:

function hisoblash(a: number | string): number {
  if (typeof a === "number") {
    return a * 2;       // ✅ bu blokda a: number
  }
  return a.length * 2;  // ✅ bu blokda a: string
}

if bloki ichida TypeScript tur biladi — faqat shu turda mavjud metodlarga ruxsat.


typeof qiymatlari

typeof x === "string"    → x: string
typeof x === "number"    → x: number
typeof x === "boolean"   → x: boolean
typeof x === "bigint"    → x: bigint
typeof x === "function"  → x: Function
typeof x === "undefined" → x: undefined
typeof x === "object"    → x: object | null  (null ham object!)

null tekshirish

typeof null === "object" — JavaScript ning eskiligi. null ni alohida tekshirish:

function uzunlik(x: string | null): number {
  if (x !== null) {
    return x.length; // ✅ bu blokda x: string
  }
  return 0;
}

// Yoki qisqaroq
function uzunlik(x: string | null): number {
  if (typeof x === "string") return x.length;
  return 0;
}

Bir nechta tur

function chiqar(x: string | number | boolean): string {
  if (typeof x === "string")  return x.toUpperCase();
  if (typeof x === "number")  return x.toFixed(2);
  return x ? "ha" : "yo'q";  // bu blokda faqat boolean qolgan
}

Truthy/falsy narrowing

function fn(x: string | null | undefined) {
  if (x) {
    x; // string — null va undefined falsy, shu blokda yo'q
  }
}

Tez-tez uchraydigan xatolar

typeof bilan ob'ektni ajratishga urinish:

function fn(x: string | Date) {
  if (typeof x === "object") {
    x; // Date | null — Date ob'ekt, lekin null ham object!
  }
}

Ob'ektlar uchun instanceof yaxshiroq (keyingi dars).


Xulosa

typeof x === "string"    → string
typeof x === "number"    → number
typeof x === "boolean"   → boolean
typeof x === "function"  → function
typeof x === "undefined" → undefined
x !== null               → null emas
x                        → truthy (null, undefined, 0, "" yo'q)

Keyingi dars

28-dars: instanceof guard — class instansini tekshirish