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

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.

Answers:

Answer

enter image description here

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]
    }
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.