Document structure of a value for arbitrary keys in an Object in JSDoc

旧城冷巷雨未停 提交于 2020-02-16 04:43:33

问题


I have a function factory:

function factory(events) {
  for(const key in events) {
    const { before, after } = events[key]
  }
}

Where the argument events is typically:

{
  only: {
    before(){}
    after(){}
  },
  except: {
    before(){}
    after(){}
  },
}

Where the keys only, except can be anything but the values are always (must be) of type {before, after} where both before, after are functions.

How do I document this structure for events argument in my factory function using JSDoc?

The only solution I can think of is to make events an array, then I can use typedef like this:

/**
 * @typedef event
 * @property {function} before
 * @property {function} after
 */
/**
 * @typedef eventTuple
 * @property {string} key
 * @property {event} event
 */
/**
 * @param {[eventTuple]} events
 */
function factory(events) {
  for(const { key, event } of events) {
    const { before, after } = event
  }
}

But I really wanna keep the original structure.

Is it possible to document this event type definition in my original structure?

I'm mainly concerned about it working in VSCode which lifts these type definitions from JSDoc.


回答1:


You can use TS syntax.

p.s. honestly, I'm not sure if this works everywhere. But it works for intellisense at least

/**
 * @typedef event
 * @property {function} before
 * @property {function} after
 */

/**
 * @param {{[key: string]: event}} events
 */
function factory(events) {
    for (const key in events) {
        const { before, after } = events[key]
    }
}


来源:https://stackoverflow.com/questions/59063496/document-structure-of-a-value-for-arbitrary-keys-in-an-object-in-jsdoc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!