Avatar ·

TypeScript में क्लास टाइप कैसे जांचें: instanceof, type guards और टाइप प्रोटेक्शन

सभी को नमस्ते! मैं TypeScript में नया हूँ और क्लास टाइप जांचने की समस्या का सामना कर रहा हूँ। मेरे पास क्लासों की एक hierarchy है: बेस क्लास `Animal` और दो child क्लास — `Dog` और `Cat`। प्रत्येक के अपने unique methods हैं: `bark()` Dog के लिए और `meow()` Cat के लिए। मुझे बाहरी स्रोत (जैसे API) से `Animal[]` टाइप का एक array मिलता है, और मुझे यह निर्धारित करना है कि प्रत्येक object किस क्लास से संबंधित है, ताकि संबंधित method को call कर सकूँ। यहाँ कोड का उदाहरण है: ```typescript class Animal { name: string; constructor(name: string) { this.name = name; } } class Dog extends Animal { bark() { console.log(`${this.name} says: Woof!`); } } class Cat extends Animal { meow() { console.log(`${this.name} says: Meow!`); } } const animals: Animal[] = [new Dog('Rex'), new Cat('Molly')]; animals.forEach(animal => { // कैसे जांचें कि animal Dog है या Cat? // if (animal instanceof Dog) { ... } — क्या यह काम करता है? // या typeof का उपयोग करना चाहिए? }); ``` समस्या यह है कि