← Back to TypeScript Course | Chapter 5: Type Aliases and Union Types | Lesson 8 of 9

instanceof का Guard

instanceof operator check करता है कि क्या एक object किसी particular class या constructor से बनाया गया था। TypeScript successful instanceof checks का उपयोग करके value को corresponding class type तक narrow करता है।
Syntax
typescript
if (variable instanceof ClassName) {
  // variable is ClassName here
}

Basic instanceof Checks

value instanceof ClassName उपयोग करें यह determine करने के लिए कि क्या एक object runtime पर एक specific class का instance है, और TypeScript उस branch के अंदर value का type narrow करता है जहां check succeed होता है।

यह काम करता है क्योंकि instanceof एक असली JavaScript runtime check है जो prototype chain पर based है, कोई ऐसी चीज़ नहीं जो TypeScript सिर्फ typing के लिए invent करता हो।

उदाहरण: Basic instanceof Checks

typescript
class Car { drive() { console.log("Driving"); } }
class Bike { pedal() { console.log("Pedaling"); } }
function move(vehicle: Car | Bike) {
  if (vehicle instanceof Car) {
    vehicle.drive();
  } else {
    vehicle.pedal();
  }
}
move(new Car());

Date के साथ instanceof

Date जैसी built-in classes को भी instanceof से check किया जा सकता है, जो उपयोगी है जब एक value का origin ambiguous हो, जैसे एक third-party library से आने वाला data जो वापस या तो एक Date object या एक plain string दे सकता हो।

उदाहरण: instanceof with Date

typescript
function printDate(value: string | Date) {
  if (value instanceof Date) {
    console.log(value.getFullYear());
  } else {
    console.log(value);
  }
}
printDate(new Date(2024, 0, 1));

Error के साथ instanceof

Error objects को आमतौर पर एक catch block में caught values handle करते समय instanceof से check किया जाता है, क्योंकि catch clauses अपने parameter को unknown type करती हैं और instanceof आपको .message पढ़ने से पहले इसे safely Error (या एक custom subclass) तक narrow करने देता है।

उदाहरण: instanceof with Error

typescript
try {
  throw new Error("Something failed");
} catch (e) {
  if (e instanceof Error) {
    console.log(e.message);
  }
}

Custom Classes के साथ instanceof

Custom classes को अक्सर discriminators के रूप में उपयोग किया जाता है जब objects के पास data के साथ behavior भी हो, instanceof को class instances के बीच उसी तरह फर्क करने देते हुए जैसे यह built-ins के बीच करता है, जो खासकर एक OOP-style codebase में कई related classes के साथ काम करते समय handy है।

उदाहरण: instanceof with Custom Classes

typescript
class Admin { manage() { console.log("Managing"); } }
class Guest { browse() { console.log("Browsing"); } }
function handle(user: Admin | Guest) {
  if (user instanceof Admin) {
    user.manage();
  } else {
    user.browse();
  }
}
handle(new Guest());

Multiple Classes के साथ instanceof

जब एक union में कई class types हों, multiple instanceof checks value को step by step narrow कर सकते हैं, if/else if branches की एक chain जैसा, जब तक कोड में हर point पर सिर्फ एक possible class न बचे।

उदाहरण: instanceof with Multiple Classes

typescript
class Circle {}
class Square {}
class Triangle {}
function name(shape: Circle | Square | Triangle): string {
  if (shape instanceof Circle) return "Circle";
  if (shape instanceof Square) return "Square";
  return "Triangle";
}
console.log(name(new Square()));
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. instanceof को एक interface या type alias के साथ उपयोग करना जैसे value instanceof Cat, जब वे runtime पर erased हो जाते हैं और सिर्फ classes (constructors) ही उपयोग किए जा सकते हैं।
  2. यह उम्मीद करना कि instanceof primitives पर काम करेगा जैसे "hi" instanceof String, जो false है क्योंकि एक primitive string एक String object नहीं है।
  3. यह मान लेना कि instanceof उन objects को match करता है जिनका merely shape same हो, जब यह prototype chain check करता है, इसलिए एक plain { drive() {} } एक Car नहीं है।
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.