टाइपस्क्रिप्ट में इससे इंस्टेंटिंग?
मुझे यकीन नहीं है कि यह संभव है, लेकिन यह वह है जिसे मैं हासिल करने की कोशिश कर रहा हूं ...
abstract class Animal<T> {
breed(mate: Animal<T>) {
return new [this kind of animal]()
}
}
class Cat extends Animal<Cat>{
}
let cat1 = new Cat();
let cat2 = new Cat();
let kitten = cat1.breed(cat2);
क्या इस प्रकार की बात संभव है, या मुझे breedहर प्रकार के जानवर के लिए एक विधि बनाने की आवश्यकता होगी ?
ES6 JS में आप उपयोग कर सकते हैं new this.constructor()लेकिन टाइपस्क्रिप्ट में यह संभव नहीं है:
abstract class Animal<T> {
breed(mate: Animal<T>) {
return new this.constructor()
}
}
एक त्रुटि देगा:
this expression is not constructable.
Type 'Function' has no construct signatures.
जवाब
(property) Object.constructor: Functionहै समारोह टाइपप्रति में आप ऐसा नहीं कर सकते, newसब के ऊपर भी पर this.constructorसे निर्माता प्रकार के मूल्य के रूप में मान्यता प्राप्त नहीं है TypeScript, लेकिन आप पर कास्ट कर सकते anyनया उदाहरण मिलता है। आपके मामले में नीचे के समान कुछ -
abstract class Animal<T> {
breed(mate: Animal<T>) {
return new (<any>this.constructor);
}
}
जावास्क्रिप्ट में हर फंक्शन को कंस्ट्रक्टर माना जाता है जब इसका उपयोग किया जाता है newइसलिए जावास्क्रिप्ट कोड बिना किसी समस्या के ठीक काम कर रहा है।