简体   繁体   中英

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.

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

截屏

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