【问题标题】:How to properly define own type of class in JSDoc?如何在 JSDoc 中正确定义自己的类类型?
【发布时间】:2018-03-12 07:05:47
【问题描述】:

我有一个简单的 ES6 类,我想知道如何在 JSDoc 中正确描述它。请注意,我想定义自己的类型,稍后会被 WebStorm 自动完成识别。

下面的例子有效吗?

/**
* @typedef {Object} View
* @class
*/
class View{...}

【问题讨论】:

    标签: javascript ecmascript-6 webstorm jsdoc


    【解决方案1】:

    这是一个非常好的问题。我今天做的方式是在其构造函数中声明我的所有类实例变量,并用其预期类型注释每个变量。这是一个很好的做法,并且与 Webstorm 配合得很好。例如:

    class MyClass {
    
        constructor () {
            /** @type {Number} some number value */
            this.someNumber = 0;
            /** @type {String} some relevant string */
            this.someString = null;
            /** @type {Map<Number, Set<String>>} map numbers to sets of strings */
            this.strSetByNumber = new Map();
        }
    
        /**
         * Some sample function.
         * 
         * @param {Number} a - first value
         * @param {Number} b - second value
         * @return {Number} the resulting operation
         */
         someFunction(a, b) {
             return a + b;
         }
    }
    

    现在只需将一些变量声明为MyClass 类型并享受自动完成功能:

    如果您尝试为某些属性分配错误的类型:


    但是,有时您甚至不需要声明一个类。比如说,例如,您希望通过 JSON 接收一个对象,并且您需要使用它。您可以使用纯 JSDoc 来帮助检查您的代码,而无需声明一个类。假设您期待这样的 JSON:

    {
        "foo": "bar",
        "fizz": 42
    }
    

    不要声明一个类,而是在代码中的某个位置执行此操作(我更喜欢将它始终放在要使用它的脚本的顶部):

    /**
     * @typedef {Object} MyType
     * @property {String} foo - this is some cool string
     * @property {Number} fizz - some number we also expect to receive
     * @property {Number} [bar] - an optional property
     */
    

    就是这样!亲自尝试一下,看看 Webstorm 如何能够很好地理解这两种方法。

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2021-02-05
      • 2018-01-20
      • 2017-08-08
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多