-->

JSDoc type for returned class instances

2019-07-15 18:40发布

问题:

I'm using Node.js with two modules and one script that depends on them:

lib/Bar.js

module.exports = class Bar {
  // ..
};

lib/Foo.js

const Bar = require('./Bar.js');

module.exports = class Foo {
  /**
   * @return {Bar} A Bar instance
  */
  get someBar() {
    return new Bar();
  }
};

main.js

const Foo = require('./lib/Foo.js');

checkFoo(new Foo());

/**
 * @param {Foo} foo A Foo instance
*/
function checkFoo(foo) {
  foo. // I get suggestions for Foo properties
  foo.someBar. // I get suggestions for Bar properties

  checkBar(foo.someBar);
}

/**
 * @param {Bar} bar a Bar instance
*/
function checkBar(bar) {
  bar. // I get no suggestions!
}

My code editor Visual Studio Code uses IntelliSense to give the user suggestions about Foo and Bar properties, which works correctly inside the checkFoo method as the type of foo is declared as Foo object, and the type of foo.someBar is declared in the Foo class as a Bar object.

But as soon as I pass this Bar instance to another method (checkBar), the type Bar isn't recognized (probably because I don't require the module). Is there a special syntax in JSDoc to specify a type as being declared in another module? Or is this just an issue with VSCode?

回答1:

Your suspicion is correct. Currently, you also need to import Bar to use its type in the jsdoc:

const Foo = require('./lib/Foo.js');
const Bar = require('./lib/Bar.js');

...

/**
 * @param {Bar} bar a Bar instance
 */
function checkBar(bar) {
    ...
}

We are tracking support for a JSDoc equivalent of require or import here: https://github.com/Microsoft/TypeScript/issues/14377