JSDOC替代返回类型的继承类方法
我试图通过将子类传递给父母来为继承方法提供动态返回类型。请在下面找到一个小例子。目前它不起作用,我认为我还不遥远。
我知道,解决方法是手动声明每个子类中的每个继承方法是一种选择,而只是从内部调用super(),但这并不像我想要的那样优雅的解决方案。
我希望有人可以帮助我找出通用类型,或者是否有可能。
提前致谢:
/**
* The Animal base class
* @class
*/
class Animal {
/**
* @param {T} classType
*/
constructor (classType) {
this.classType = classType
}
/**
* @returns {T} A baby of the same type as the parent instance
*/
giveBirth () {
return new this.classType()
}
}
/**
* The Dog class
* @class
* @extends Animal
*/
class Dog extends Animal {
constructor () {
super(Dog)
}
bark () {
return 'woof'
}
}
const dog = new Dog()
const babyDog = dog.giveBirth()
babyDog.bark() // JSDoc does not consider it an instance of Dog
I'm trying to provide a dynamic return type for an inherited method by passing the child Class to the parent. Please find a small example below. Currently it's not working and I'm thinking I am not far off.
I'm aware that a workaround is to manually declare each inherited method in each child class is an option, and simply calling super() from within but that's not as elegant a solution as I was hoping for.
I'm hoping someone can help me figure out the generic types or if it's at all possible.
Thanks in advance:
/**
* The Animal base class
* @class
*/
class Animal {
/**
* @param {T} classType
*/
constructor (classType) {
this.classType = classType
}
/**
* @returns {T} A baby of the same type as the parent instance
*/
giveBirth () {
return new this.classType()
}
}
/**
* The Dog class
* @class
* @extends Animal
*/
class Dog extends Animal {
constructor () {
super(Dog)
}
bark () {
return 'woof'
}
}
const dog = new Dog()
const babyDog = dog.giveBirth()
babyDog.bark() // JSDoc does not consider it an instance of Dog
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加
@template
Animal
并正确扩展(@Extends Animal< dog>
)为我工作Adding
@template
forAnimal
and correct extend (@extends Animal<Dog>
) works for me