0

I'm trying to do the following: I have an object that looks like that

const object = {
    healthcheck: [
        { method: 'get', name: 'test' }
    ],
    users: [
        { method: 'get', name: 'auth' }
    ],
};

So I have an object that has keys, each key can be any string, and each key is an array of objects that has method and name as keys.

How can I use JSDoc to give intellisense with a dynamic key inside the object?

Thanks!

Asaf
  • 949
  • 2
  • 13
  • 14

1 Answers1

1

You can type hint dynamic keys by this syntax: {[key: string]: any}, so in your case, this should get the result you're looking for:

/**
 * @typedef {{
 *     [key: string]: [{
 *         method: string,
 *         name: string
 *     }]
 * }} MyObject
 */

/**
 * @type {MyObject}
*/
const object = {
    healthcheck: [
        { method: 'get', name: 'test' }
    ],
    users: [
        { method: 'get', name: 'auth' }
    ],
}

The typedef is for convenience of using the type in various places in your code, but if you need intellisense to show the full shape of the type, you can use the type directly:

/**
 * @param {{
 *     [key: string]: [{
 *         method: string,
 *         name: string
 *     }]
 * }} routes
 */
const xt = routes => {}
Michael Horn
  • 3,819
  • 9
  • 22
  • Hey, thanks! but if I'm trying to create a function that accepts this MyObject. I don't see any intellisense, see image below: [image.png](https://postimg.cc/ZBBFbyhW) It shows only "MyObject" – Asaf Jul 16 '21 at 16:55
  • Np! I edited the answer to add an alternative that should hopefully do it – Michael Horn Jul 16 '21 at 17:05
  • Thanks! do you know if there's any way to make it autocomplete what you type as a key? such as @template? [![image.png](https://i.postimg.cc/FKBD5G4W/image.png)](https://postimg.cc/7CSgS3b0) – Asaf Jul 17 '21 at 07:48