Seriya: TypeScript Basics Dars 43

instanceof type guard

TypeScript'da instanceof type guard: class instance'larini ajratish, null'ning avtomatik chiqib ketishi, DOM elementlari, merosda tekshiruv tartibi, type/interface bilan ishlamasligi va catch'da instanceof Error.

43-dars

instanceof type guard

typeof obyektlar uchun faqat "object" qaytaradi va Date'ni Map'dan yoki <input>'ni <div>'dan ajrata olmaydi. DOM elementini as bilan "majburlash" xavfli ekanini ko'rgan edik:

// ❌ as — TS'ga "ishon" deyish, tekshirish emas
const el = document.querySelector("#email") as HTMLInputElement;
console.log(el.value.trim());
// Element topilmasa: 💥 TypeError: Cannot read properties of null (reading 'value')
// #email aslida <div> bo'lsa: el.value — undefined, .trim() da yana 💥

instanceof esa runtime'da haqiqatan tekshiradi va TS natijaga qarab type'ni toraytiradi:

// ✅ instanceof — haqiqiy tekshiruv
const el = document.querySelector("#email"); // Element | null

if (el instanceof HTMLInputElement) {
  console.log(el.value.trim()); // el: HTMLInputElement
} else {
  console.warn("#email input topilmadi");
}

Bitta tekshiruv ikki muammoni hal qiladi: null ham, noto'g'ri element ham elsega tushadi.

Qanday ishlaydi?

1. x instanceof Class — "x shu class'dan yaratilganmi?"

instanceof JS operatori bo'lib, obyektning prototip zanjirida shu class bor-yo'qligini tekshiradi. TS esa true tarmog'ida type'ni o'sha class instance'iga toraytiradi:

function sanaFormatla(sana: Date | string): string {
  if (sana instanceof Date) {
    return sana.toLocaleDateString("uz-UZ"); // sana: Date
  }
  return new Date(sana).toLocaleDateString("uz-UZ"); // sana: string
}

O'ng tomonda doim class (constructor funksiya) turadi: Date, Map, Error, HTMLElement va h.k.

2. null va undefined avtomatik chiqib ketadi

null instanceof Istalgan doim false. Shuning uchun alohida null tekshiruvi kerak emas:

function keshdan(k: Map<string, number> | null | undefined) {
  if (k instanceof Map) {
    return k.size; // Map<string, number> — null va undefined chiqib ketdi
  }
  return 0;
}

typeof x === "object" tuzog'idan farqli o'laroq, bu yerda null hech qachon o'tib ketmaydi.

3. DOM elementlari bilan

DOM'dagi har bir element turi alohida class: HTMLInputElement, HTMLSelectElement, HTMLButtonElement... Bu esa instanceof'ni DOM bilan ishlashda asosiy vositaga aylantiradi:

function qiymatOl(id: string): string | null {
  const el = document.getElementById(id); // HTMLElement | null

  if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {
    return el.value; // HTMLInputElement | HTMLTextAreaElement — ikkalasida ham value bor
  }
  if (el instanceof HTMLSelectElement) {
    return el.options[el.selectedIndex]?.text ?? null; // ?. va ??
  }
  return null;
}

4. Meros: avval aniqroq class'ni tekshiring 🐛

instanceof ota class uchun ham true qaytaradi. TypeError — Error'ning bolasi, shuning uchun tartib muhim:

function xatoTuri(e: Error): string {
  if (e instanceof Error) {
    return "umumiy xato";
  } else if (e instanceof TypeError) {
    return "type xatosi"; // 🐛 hech qachon bajarilmaydi: TypeError ham Error
  }
  return "?";
}
// ✅ Bola class'lar birinchi, ota class oxirida
function xatoTuri(e: Error): string {
  if (e instanceof TypeError) return "type xatosi";
  if (e instanceof RangeError) return "diapazon xatosi";
  return "umumiy xato";
}

5. type va interface bilan ishlamaydi

type va interface faqat compile vaqtida mavjud, runtime'da ular yo'q. instanceof esa runtime operatori:

type Foydalanuvchi = { ism: string };

function salom(x: unknown) {
  if (x instanceof Foydalanuvchi) {
    // ❌ 'Foydalanuvchi' only refers to a type, but is being used as a value here.
  }
}
typeof instanceof
Nimani tekshiradi Primitive turi Class'dan yaratilganmi
null "object" ⚠️ doim false ✅
Oddiy obyekt type'lari (type, interface) ajrata olmaydi ishlatib bo'lmaydi
Ular uchun vosita discriminated union, custom guard discriminated union, custom guard

Eng ko'p uchraydigan xato

catch blokida error.message'ni tekshirmasdan ishlatish.

async function yukla() {
  try {
    await saqlash();
  } catch (error) {
    console.error(error.message);
    // ❌ 'error' is of type 'unknown'.
  }
}

Nega bunday bo'ladi? JS'da throw bilan istalgan narsa otilishi mumkin: throw "xato", throw 404, throw { code: 1 }. Shuning uchun strict rejimida TS error'ni unknown deb hisoblaydi. Type annotation bilan aldash ham ishlamaydi:

try {
  await saqlash();
} catch (error: Error) {}
// ❌ Catch clause variable type annotation must be 'any' or 'unknown' if specified.

Ko'pchilik bu xatoni as bilan "yopadi":

try {
  await saqlash();
} catch (error) {
  showToast((error as Error).message);
  // 🐛 kutubxona throw "Timeout" qilsa — .message undefined, foydalanuvchi bo'sh xabar ko'radi
}

✅ Yechim: instanceof Error bilan tekshiring, qolgan holatlarni ham qayta ishlang

try {
  await saqlash();
} catch (error) {
  if (error instanceof Error) {
    showToast(error.message); // error: Error
  } else {
    showToast(String(error)); // "Timeout", "404" va h.k.
  }
}

Bu loyihada ko'p takrorlansa, kichik yordamchi funksiyaga chiqaring:

function xatoXabari(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}

try {
  await saqlash();
} catch (error) {
  showToast(xatoXabari(error)); // ✅
}

Esda tuting: catch'dagi error — unknown, unga as emas, instanceof Error bilan murojaat qiling va Error bo'lmagan holatni ham qayta ishlang.