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

enter image description here

Upvotes: 3

Views: 119

Answers (1)

lepsch
lepsch

Reputation: 10319

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

Screenshot

Upvotes: 2

Related Questions