繁体   English   中英

JSDoc覆盖继承类方法的返回类型

[英]JSDoc override return type of inherited class method

我试图通过将子类传递给父类来为继承的方法提供动态返回类型。 请在下面找到一个小例子。 目前它不起作用,我想我离得不远了。

我知道一种解决方法是手动声明每个子类中的每个继承方法是一个选项,并且只需从内部调用 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

Animal添加@template并正确扩展( @extends Animal<Dog> )对我有用

/**
 * The Animal base class
 * @class
 * @template T
 */
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<Dog>
 */
class Dog extends Animal {
    constructor () {
        super(Dog)
    }

    bark () {
        return 'woof'
    }
}

const dog = new Dog()
const babyDog = dog.giveBirth()
babyDog.bark()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM