简体   繁体   中英

JSdoc: Dynamic key name of return object


/**
 * 
 * @param {string} key 
 * @param {any} value
 * @returns {{[key]: typeof value}} 
 */
const set = (key, value) => {
    return {[key]: value}
}

const myObj = set("country", "USA")

myObj. // should suggest .country key

I can not understand how correct define key name of return object

在此处输入图像描述

The following would do the trick. Just use @template to type it as a generic function.

/**
 * @template {string} K
 * @template T
 * @param {K} key
 * @param {T} value
 * @returns {Record<K, T>}
 */
const set = (key, value) => {
  return {[key]: value}
}

截屏

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