JSDoc 在实例化后将某些东西标记为 Class 并定义构造函数属性

JSDoc Mark something as Class after instantiation and define constructor properties

我让猫鼬为我创建了一个模型(class),我想让class有智能感知。问题是我不知道如何将某些东西标记为 class,以及如何为 class.

键入构造函数

查看 JSDocs 的文档,他们只指定如何在声明中键入 class,而不是在它已经被实例化时。 @class@constructor 标签似乎没有任何作用。

现在我通过将它标记为一个函数(它在引擎盖下,但在 VSC 中拥有正确的颜色仍然很棒)并定义参数来获得我的智能感知:

/**
 * @typedef QPE_Opts
 * @type {object}
 * @prop {string} id - Id of the user 
 * ...
 */
/**
 * @type {function(QPE_Opts) : mongoose.Model<mongoose.Document, {}> }}
 */
const Queue_PoolEntry = mongoose.model('Queue_PoolEntry', Queue_PoolEntrySchema);

解决方案

解决方案(正在查看未提供足够信息的 JsDocs 文档,感谢@Graham P Heath 提供 the better docs):

/**
 * @type {function(new:mongoose.Model<mongoose.Document, {}>, QPE_Opts ) }}
 */

如果您确定对象的类型,您可以type cast它:

const Queue_PoolEntry = /** @type {QPE_Opts} */ (mongoose.model('Queue_PoolEntry', 
    Queue_PoolEntrySchema));

在您实际上无法确定返回的类型转换的情况下,可能是代码异味。在这种情况下:使用代码通过检查对象的预期属性来确定类型断言的有效性,然后再强制转换它。

let Queue_PoolEntry = mongoose.model('Queue_PoolEntry', 
    Queue_PoolEntrySchema);
if (Queue_PoolEntry && Queue_PoolEntry.id) {
  Queue_PoolEntry = /** @type {QPE_Opts} */ (Queue_PoolEntry)
} else {
  throw new Error('mongoose.model(\'Queue_PoolEntry\', Queue_PoolEntrySchema)'+
      'returned something other than a QPE_Opts' + Queue_PoolEntry);
}