[FIXED] JSDoc with typescript, defining custom object key type doesn't raise error

Issue

Adding anything other than generic types doesn’t type check on key-map objects

Example:

/**
 * @typedef {"MARKET1"|"MARKET2"|"MARKET3"} Market
 * @typedef {{
    name: string,
   }} Item

  this type checks just items, not keys
 * @typedef {{
    items: Object.<string, Item[]>,
   }} Config
   
  this doesn't type check anything, even items
  having a non generic type in the key field doesn't raise any error
 * @typedef {{
    items: Object.<Market, Item[]>
   }} Config  
*/

Solution

Just use the utility type Record instead of Object.<key, value>. It’s going to be like the snippet below:

/**
 * @typedef {"MARKET1"|"MARKET2"|"MARKET3"} Market
 * @typedef {{
    name: string,
   }} Item
 */

/**
 * @typedef {{
  items: Record<string, Item[]>,
 }} Config1
 */

/**
 * @typedef {{
  items: Record<Market, Item[]>
 }} Config2
 */

enter image description here

enter image description here

Answered By – lepsch

Answer Checked By – Marilyn (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published