简体   繁体   中英

Dynamic key name inside an object

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! 😉

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 => {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM