instanceof guard — class instanсini tekshirish

~15 daq · TypeScript · Type Narrowing

catch blokida xato qanday tur ekanini bilmaysiz — Error, TypeError, yoki boshqacha. typeof yordamida ob'ektlarni aniqlab bo'lmaydi — barcha ob'ektlar "object". Buning uchun instanceof guard.


instanceof nima?

x instanceof SomeClass — x ning SomeClass instansi ekanligini tekshiradi. TypeScript bu blokda x ni shu tur sifatida biladi:

function xatoIshlash(e: unknown): string {
  if (e instanceof TypeError) {
    return `Tur xatosi: ${e.message}`;
  }
  if (e instanceof Error) {
    return `Xato: ${e.message}`;
  }
  return "Noma'lum xato";
}

try {
  JSON.parse("{noto'g'ri}");
} catch (e: unknown) {
  console.log(xatoIshlash(e));
}

O'z classlari bilan

class It {
  zot: string;
  constructor(zot: string) { this.zot = zot; }
  ovoz() { return "Vov!"; }
}

class Mushuk {
  rang: string;
  constructor(rang: string) { this.rang = rang; }
  ovoz() { return "Miyov!"; }
}

function tavsif(h: It | Mushuk): string {
  if (h instanceof It) {
    return `It: ${h.zot}`; // ✅ h: It
  }
  return `Mushuk: ${h.rang}`; // ✅ h: Mushuk
}

instanceof va meros zanjiri

Ota-class instansi ham mos keladi:

class Hayvon { ism = ""; }
class It extends Hayvon { zot = ""; }

const it = new It();
it instanceof It;      // true
it instanceof Hayvon;  // true — It, Hayvon dan meros olgan

Shu sababli ota-classni if da keyin tekshirish kerak:

if (e instanceof TypeError) { ... }  // avval aniqroq
if (e instanceof Error)     { ... }  // keyin umumiy

typeof vs instanceof

typeof     → primitive (string, number, boolean, undefined)
instanceof → ob'ekt va class (Error, Date, Set, MyClass...)
function fn(x: string | Date | null) {
  if (typeof x === "string") { /* string */ }
  if (x instanceof Date)     { /* Date   */ }
  if (x === null)            { /* null   */ }
}

Tez-tez uchraydigan xatolar

Interface bilan instanceof:

interface Foydalanuvchi { ism: string; }

function fn(x: unknown) {
  if (x instanceof Foydalanuvchi) { } // ❌ — interface runtime da yo'q
}

instanceof faqat class bilan ishlaydi. Interface uchun in operator yoki type predicate.

catch da e: unknown tekshirmasdan ishlatish:

catch (e) {            // ❌ — e: any, tekshiruv yo'q
  console.log(e.message);
}

catch (e: unknown) {   // ✅ — tekshirish majburiy
  if (e instanceof Error) console.log(e.message);
}

Xulosa

if (x instanceof Error)   { x.message; x.stack; }
if (x instanceof Date)    { x.getTime(); }
if (x instanceof MyClass) { x.myMethod(); }

// catch bloki — har doim unknown
catch (e: unknown) {
  if (e instanceof Error) { /* ... */ }
}

// Meros: aniqdan umumiyga
if (e instanceof TypeError) { ... }
if (e instanceof Error)     { ... }

Keyingi dars

29-dars: in operator guard — xususiyat mavjudligini tekshirish