简体   繁体   English

对象内的动态键名

[英]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?如何使用 JSDoc 在对象内部使用动态键提供智能感知?

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:您可以通过以下语法输入提示动态键: {[key: string]: any} ,因此在您的情况下,这应该会得到您正在寻找的结果:

/**
 * @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: typedef 是为了方便在你的代码中的各个地方使用类型,但是如果你需要智能感知来显示类型的完整形状,你可以直接使用类型:

/**
 * @param {{
 *     [key: string]: [{
 *         method: string,
 *         name: string
 *     }]
 * }} routes
 */
const xt = routes => {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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