Dartnix
Dartnix

Reputation: 117

How to inherit method types from parent class with JsDoc?

I'd like to be able to write the JsDoc for an abstract method in the parent class, such that it applies to all its inheritors.

This example is an extremely stripped-down version of my case:

class Shape {
    /** Does some complicated example stuff.
     * @param {number} myNumber a real value.
     * @param {boolean} myBoolean a flag.
     * @param {string} myString some text.
     * @returns {string} something important.
     */
    doStuff(myNumber, myBoolean, myString) {}
}

The doStuff method is not implemented, because each of the (many) subclasses implements it differently, but with the same signature and the same parameters.

class Triangle extends Shape {
    doStuff(myNumber, myBoolean, myString) {
        return myBoolean ? myNumber.toString() : myString;
    }
}

As you can see from the screenshot, the text parts of the documentation are inherited, but the parameter types and return type are lost. What can I do to correctly inherit the types as well? I tried playing around with the @inheritdoc, @abstract, @extends, @override and @link tags but with no success.

VScode not carrying types over

Please consider that this is an extremely simplified version, in my actual code the documentation block is upwards of 20 lines and copying it over to an ever-increasing number of subclasses is not feasible as it would be a nightmare to maintain.

Upvotes: 5

Views: 2906

Answers (3)

Mat
Mat

Reputation: 1101

The following pattern will work (though admittedly not perfect)

class Triangle extends Shape {
    /** @type {Shape['doStuff']} */
    doStuff(myNumber, myBoolean, myString) {
        return myBoolean ? myNumber.toString() : myString;
    }
}

Upvotes: 5

Stefan Walter
Stefan Walter

Reputation: 126

I don't think this is possible, as this is a shortcoming of JSDoc.

It's anyway arguable that parameter types should be taken from the respective base class function.

Upvotes: 1

vivatjavascript
vivatjavascript

Reputation: 11

How about you wrap your doStuff() method inside it's own @typedef?

https://jsdoc.app/tags-typedef.html

/**
* @typedef doStuff
* @type {Function}
* @param {Number} myNumber
* @param {Boolean} myBoolean
* @param {String} myString
* @returns {String}
*/

And then use it in extends:

class Triangle extends Shape {
  /** @type {doStuff} */
  doStuff(){}
}

Upvotes: 1

Related Questions