【问题标题】:JSDoc: how to define a type that's equal to object's property names- like Typescript's keyof?JSDoc:如何定义一个等于对象属性名称的类型——比如 Typescript 的 keyof?
【发布时间】:2022-07-23 12:50:43
【问题描述】:

我正在寻找一种使用 JSDoc 将对象的属性名称作为类型获取的方法。

设一个名为Record的对象的typedef

/**
 * @typedef {{
      date: string,
      a1: string,
      a2: string,
   }} Record
 */

我希望将变量 fields 记录为等于对象的属性 - 这意味着对于本示例:'date' | 'a1' | 'a2'

/**
 * @type {*keyof Record??*} in this case, this will be equal to @type {'date' | 'a1' | 'a2'}
 */
let fields = 'a1';

Typescript 提供了 keyof 关键字,它就是这样做的。不幸的是,我正在使用的系统不支持打字稿:\

【问题讨论】:

    标签: javascript typescript types jsdoc


    【解决方案1】:
    /*
    * @typedef {{
    * date: string,
    * a1: string,
    * a2: string,
    * }} Record
    */
    
    /** @type {Record['date']|Record['a1']|Record['a2']}*/
    let fileds = 'a1';
    

    试试这个

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 2020-04-14
      • 2020-03-17
      • 2020-12-29
      • 1970-01-01
      • 2012-11-04
      • 2023-04-07
      相关资源
      最近更新 更多