109

Having next example:

var CONF = {
    locale: {
        "en": {
            name: "English",
            lang: "en-US"
        },
        "es": {
            name: "Spanish",
            lang: "es-ES"
        }
    }
};

And knowing that what the locale property contains is a dictionary object, which comes from the database, how can I document its inner properties with JSDoc?

Currently I am thinking to typedef type for my locale objects, then may I be able to set the locale property to simply an Array of my defined type? Is this the right way to do it?

Áxel Costas Pena
  • 5,886
  • 6
  • 28
  • 59

2 Answers2

182

According to the JSDoc 3 docs:

Arrays and objects (type applications and record types)

An object with string keys and number values:

{Object.<string, number>}

So it would be:

/** @type {{locales: Object.<string, {name: string, lang: string}>}} */
var CONF = {
    locales: {
        en: {
            name: "English",
            lang: "en-US"
        },
        es: {
            name: "Spanish",
            lang: "es-ES"
        }
    }
};

Cleaner, using @typedef

/**
 * @typedef {{name: string, lang: string}} locale
 */
/**
 * @type {{locales: Object.<string, locale>}}
 */
var CONF = {
    locales: {
        en: {
            name: "English",
            lang: "en-US"
        },
        es: {
            name: "Spanish",
            lang: "es-ES"
        }
    }
};
gp.
  • 8,074
  • 3
  • 38
  • 39
Áxel Costas Pena
  • 5,886
  • 6
  • 28
  • 59
3

As far as I can tell:

Using @typedef and @property to define a custom type is the "correct" way in JSDoc. But it is cumbersome to write and ugly to read (a cardinal sin in documentation).

The record type is much neater (note the double {{s):

   /** {{
         name:string, 
         lang:string
   }} */
Yves M.
  • 29,855
  • 23
  • 108
  • 144
Daniel Winterstein
  • 2,418
  • 1
  • 29
  • 41
  • 3
    Hmmm... this documents a singe entry in the locale object, am I wrong? BTW that comment [doesn't validate](http://orgachem.github.io/jsdoctypeparser/) because of the lang description, you should remove it ;) – Áxel Costas Pena Oct 29 '13 at 08:41
  • You're not wrong! I thought that was the most useful snippet to give you, since the locale var is a map of custom-type locale objects. – Daniel Winterstein Oct 29 '13 at 09:30
  • If the Dictionary is based on array it can be {Array<{key:string, value:{name:string, lang:string}}>} or {{key:string, value:{name:string, lang:string}}[]}... still object are tend to be dictionary of key values in java-script, and in my case, and ÁxelCostasPena scenario, i rather like to go with ÁxelCostasPena solution. – Hassan Faghihi Jan 14 '20 at 07:30