0

Say I have this function:

function wrapInObject(key){
  const result = { [key]: key }
  return result
}

and I have this code:

const a = wrapInObject("Yellow")
a.Yel.. // <--- as I'm writing, the intellisense shows "Yellow"

I want to get intellisense from the code editor I'm using about the return value of this object, so as soon as I write "Yel" the code editor will autocomplete and show me the option "Yellow" to choose.

How to write this logic in jsDoc?

I have tried the following, but I stopped because I didn't know how to complete this:

/**
 * @param {string} key - the string to wrap inside an object
 * @returns { ??? }
*/
function wrapInObject(key){
  const result = { [key]: key }
  return result
}

Is there something like

  @returns {result}

I'm unable to wrap my head around it.

I appreciate your help .

Update:

I noticed many of you didn't get the point of my question.

I don't want "Yellow" to be hard-coded, someone might input "Orange", or "Boy", or "House" or anything.

It should be dynamic, not static

Normal
  • 1,616
  • 15
  • 39

2 Answers2

1

You can use generic type for this purpose

/**
 * @template {string} T
 */
function wrapInObject(/**@type {T}*/key) {
  const result = /**@type {{[k in T]: T}}*/({ [key]: key });
  return result;
}

You can also replace {[k in T]: T} on Record<T,T> if you want

TypeScript playground

enter image description here

maksimr
  • 4,891
  • 2
  • 23
  • 22
-2

Here you can see great example of @typedef:

/**
 * @typedef {Object} wrappedObject
 * @property {string} Yellow
 */

/**
 * @return {wrappedObject} wrappedObject - {@link wrappedObject}
 */
function wrapInObject(key){
  const result = { [key]: key }
  return result
}

I have not tested this code yet

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • you're hard-coding "Yellow", that's why I'm asking. I don't want "Yellow" to be hard-coded in JSDoc, it should be dynamic, someone might input "Orange", or "House". That's why my question isn't answered. – Normal Jan 05 '23 at 09:10
  • @Normal So that's like runtime specific values, you can't write it into documentation beforehand. Imagine that values will be coming from user input in remote server. How can your local interpreter know it? – Justinas Jan 05 '23 at 09:16
  • I know, I can't answer this question because I don't know typescript, but I have used many packages written in typeScript, and people were donig my example above, for example redux toolkit, it can detect many things based on your input in your code – Normal Jan 05 '23 at 10:13
  • @Normal You can detect it if you would pass in always same structure object – Justinas Jan 05 '23 at 10:17
  • this looks really complex :;( – Normal Jan 05 '23 at 10:22