【问题标题】:JSDoc Mark something as Class after instantiation and define constructor propertiesJSDoc 在实例化后将某些东西标记为 Class 并定义构造函数属性
【发布时间】:2020-12-14 11:53:57
【问题描述】:

我让猫鼬为我创建了一个模型(类),我想让这个类有智能感知。问题是我不知道如何将某物标记为类,以及如何键入该类的构造函数。

查看 JSDocs 的文档,他们只指定如何在声明中键入一个类,而不是在它已经被实例化时。 @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 ) }}
 */

【问题讨论】:

    标签: javascript types jsdoc


    【解决方案1】:

    如果您确定对象的类型,您可以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);
    }
    

    【讨论】:

    • &gt;The problem is I don't know how to mark something as a class, and how to type the constructor for that class. mongoose.model 总是返回一个类。如果无法访问类声明,我不知道如何键入类。我想typecast 到一个类 并键入它的constructor。目前,我通过将其类型转换为 function 来伪造它,该函数存在 new 关键字 不起作用等问题。我的问题是 不是如何进行类型转换但是如何声明一个自定义类型,它是一个带有类型化构造函数的类
    • 要将任何内容标记为另一种类型,您可以对其进行类型转换。要创建一个类型,你的类型 def 对我来说看起来不错,但如果它没有阅读文档:github.com/google/closure-compiler/wiki/…你想将一些东西作为一个类输入,这样做会改变其构造函数的属性。最后,@class@constructor 早于 ES6,在 ES6 类和构造函数中没有位置。
    • 文档使它工作,必须使用function(new:...)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    相关资源
    最近更新 更多