【问题标题】:How to document destructured variable with jsdoc如何使用 jsdoc 记录解构变量
【发布时间】:2022-04-26 18:17:17
【问题描述】:

我有这样的事情:

let { total } = settings;

如何记录总变量?我尝试过这样的事情:

/**
 * @type {Object}
 * @property {String} total.test
 */
let { total } = settings;

但这似乎不是正确的方法。

有什么建议吗?

【问题讨论】:

  • 考虑到解构可以同时声明多个变量,所以也许您需要将 jsdoc 移动到对象大括号内?
  • @Bergi 你的意思是这样的吗:let { /** * @type {Object} * @property {String} total.test */ totalInCart } = mincartSettings; 如果是这样,它似乎也不起作用。
  • 这就是我会尝试的,但我不知道。
  • 没有解决办法?我也在寻找如何解决这个问题。我猜人们转向打字稿而不是找到解决方案。

标签: javascript jsdoc


【解决方案1】:

@Tommy-Pepsi Gaudreau 在他对原始问题的评论中非常接近。

这是example in the closure compiler tool @ closure-compiler.appspot.com

let /** @type {Object<string|boolean>} */ settings = {};
let str = 'string';
let bool = true;
settings.b = bool;
settings.s = str;

// Note that at this point, b and s are of the type {string|boolean}.

let {/** @type {string} */ s,/** @type {boolean} */ b } = settings;

console.log({b, s});

// But now, when we assign the wrong types, we get a warning.

b='warn';
s=false;

警告数:2

JSC_TYPE_MISMATCH: assignment
found   : string
required: boolean at line 15 character 4
    b='warn';
    ^
JSC_TYPE_MISMATCH: assignment
found   : boolean
required: string at line 16 character 4
    s=false;
    ^

编辑 - 2018 年 9 月 27 日:我减少了初始输入的数量以确保/澄清类型不会被忽略,并且警告来自解构中的类型.

【讨论】:

  • 从实验上看,Typescript 似乎没有解析这个答案中显示的标签——它是否可以理解另一种语法?
【解决方案2】:

对于任何直接解构的变量,您可以尝试此解决方法

/**
 * @typedef {object} DestructuredVariable
 * @property {string} total
 */
/** @type {DestructuredVariable} */
const {total} = getUser();

【讨论】:

    【解决方案3】:

    简单地内联JSDoc块解构块中:

    const {
    
      /**
       * The answer to everything
       * @type {number}
       */
      a,
    
      /**
       * The perfect food container
       * @type {string}
       */
      b,
      
      /**
       * Some other stuff
       * @type {object}
       * @property {string} foo Random text
       * @property {boolean} baz Random flag
       */
      c
    } = {a: 42, b: 'burrito', c: { foo: 'bar', baz: true }};
    

    VS Code 的截图:

    使用yarn jsdoc file1.js生成的文档

    【讨论】:

      【解决方案4】:

      如果你想记录一个对象,简单的答案是:

      /**
       * @type {{total: String}}
       */
      let { total } = settings;
      

      更多详情请查看JS-Documentation

      【讨论】:

        猜你喜欢
        • 2018-01-29
        • 1970-01-01
        • 2016-06-03
        • 2020-10-22
        • 2020-05-21
        • 2019-04-06
        • 2012-11-04
        • 2021-02-20
        • 2013-05-30
        相关资源
        最近更新 更多