【问题标题】:JSDoc, treat POJO as instance of ClassJSDoc,将 POJO 视为 Class 的实例
【发布时间】:2018-06-15 21:26:00
【问题描述】:

我有一个类和一个函数,该类的实例或类似的 POJO 对象作为参数。

我想用 JSDoc 注释这个函数。

class Test {
    constructor(a, b) {
        this.a = a;
        this.b = b;
    }
}

/**
 * @param {Test} test
 */
function handleTest(test) {
    console.log(test.a, test.b);
}

// Webstorm complains that argument is not of type Test
handleTest({
    a: 'this is a'
});

使用@param {Test} test几乎可以工作...但 WebStorm 抱怨 POJO 不能分配给类型 Test。

我可以做一些 JSDoc 技巧来明确Test 的实例和类似Test 的对象都可以吗?

【问题讨论】:

    标签: javascript ecmascript-6 webstorm jsdoc


    【解决方案1】:

    使用type union:

    /**
     * @param {Test|{a,b}} test
     */
    function handleTest(test) {
      console.log(test.a, test.b);
    }
    

    类型的|{a,b} 部分表示单独的允许类型。您可以只使用{Test|{}},但IDE 不知道ab 是预期属性。

    这是速记版本;如果您计划在多个地方使用和记录 TestLike 对象,您还可以定义什么是“类测试”对象:

    /**
     * @typedef {object} TestLike
     * @property {string} a - some property a
     * @property {string} b - some property b
     */
    
    /**
     * @param {Test|TestLike} test
     */
    handleTest(test) {
      // ...
    }
    

    【讨论】:

    • 是的,但是我必须注释所有对象的重复项——一次在 cmets 中,一次在课堂上。重点是能够使用 Class 作为注解,所以当 Class 发生变化时,IDE 会警告我我的函数调用错误。
    • 明白你在说什么,但我不确定有什么方法可以达到 100%
    猜你喜欢
    • 2020-12-14
    • 2016-04-02
    • 2015-02-16
    • 2012-11-24
    • 2018-01-12
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多