Search code examples
javascriptecmascript-6documentationjsdoc

In JSDoc, how to apply param type as bunch of strings from a constant array of objects string property?


Let's say I have an object like this;

const typesOfIceCreams = [
 {id: "CHOCOLATE", price: 0.49, rating: 4.5},
 {id: "CHERRY", price: 0.54, rating: 4.3},
 {id: "LEMON", price: 0.44, rating: 4.6},
]

I want to get an object from typesOfIceCreams array by id property. So I have a function like this;

/**
* @param {?} iceCreamId
*/
const getIceCreamById = (iceCreamId) => {
 return typesOfIceCreams.find(iceCream => iceCream.id === iceCreamId);
}

* @params { "CHOCOLATE" | "CHERRY" | "LEMON" } iceCreamId

I could have written like this. But it is time-consuming whenever I want to add new ice cream data to the array. I would like something similar to this;

* @params { typesOfIceCreams.map(iceCream => iceCream.id) }

Thus, I will be able to see that three options ("CHOCOLATE" | "CHERRY" | "LEMON") whenever I try to call getIceCreamById() function.


Solution

  • The following should do the trick. Just cast the array to const.

    const typesOfIceCreams = /** @type {const} */([
      {id: "CHOCOLATE", price: 0.49, rating: 4.5},
      {id: "CHERRY", price: 0.54, rating: 4.3},
      {id: "LEMON", price: 0.44, rating: 4.6},
    ])
    
    /**
    * @param {typeof typesOfIceCreams[number]['id']} iceCreamId
    */
    const getIceCreamById = (iceCreamId) => {
     return typesOfIceCreams.find(iceCream => iceCream.id === iceCreamId);
    }
    

    Screenshot