skip to Main Content

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

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search