Javascript + JsDoc: How to document new ES6 datatypes like map?
Asked Answered
F

3

17

I'm trying to use JSDoc in my ES6 project, I'm returning a Map:

/**
 * Some documentation.. 
 *
 * @returns {undefined} <- This should be replaced
 */
function returningMap() {
    const someMap = new Map();
    someMap.set("key", {a, b, c});
    return someMap;
}

How should I document this with @returns?

There is not good answer here.

Freewill answered 12/7, 2016 at 6:41 Comment(1)
I have a nearly similar problem. #38309623Tumefaction
H
22

The answer is simple and beautiful:

/**
 * Some documentation.
 *
 * @return {Map<String, Object>}
 */
function returningMap() {
    const someMap = new Map();
    someMap.set("key", {a, b, c});
    return someMap;
}

The basic pattern is Map<KeyType, ValueType>. From your example, key would be a string and value an object. You could even go ahead and declare your object as well. For instance:

/**
 * @typedef {Object} MyObject
 * @property {Number} a
 * @property {Number} b
 * @property {String} c
 */

And then your map would be declared as Map<String, MyObject>. Cool, isn't, it? You could also nest other maps or even sets, like Map<Number, Set<MyObject>>.

Hydrophilous answered 1/10, 2017 at 20:49 Comment(0)
P
1

Your best bet is probably to define Map and friends with @external somewhere:

/**
 * The Map object is a simple key/value map. Any value (both objects and primitive values) may be used as either a key or a value.
 * @external Map
 * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map}
 */

Then your type will be defined, so you can say @returns {Map} as the comments say.

A convenient place to get all the URLs and one-liners in one place is from tern.

Propinquity answered 18/7, 2016 at 22:54 Comment(0)
T
0

In the case of predefined map's keys You may also use '@typedef' as key list enum and [non-iterable] 'Record' instead of [iterable] 'Map'

/**
 * @typedef {'AE' | 'BE' | 'BG'} BUILDING_TAG
 */
/**
 * Buildings
 * @type {Record<BUILDING_TAG, {name:string}>}
 */
const BUILDINGS = {
    'A' : { name: 'Building А' },
    'B' : { name: 'Building B' },
    'C' : { name: 'Building C' }
};

/**
 * @typedef {'SNR' | 'ELTEX' | 'TPLINK'} SWITCH_TYPE
 */
/** 
 * @typedef SWITCH
 * @property {string} ipAddress
 * @property {SWITCH_TYPE} type
*/

/** @type { {switches: Record<BUILDING_TAG,SWITCH[]>, other: string} } */
var CONF = {
    switches: {
        'A': 
            [
                {ipAddress: '1.2.3.4', type: 'SNR'},
                {ipAddress: '1.2.3.5', type: 'SNR'}
            ],
        'B': 
            [
                {ipAddress: '1.2.3.4', type: 'ELTEX'}
            ],
        'C': 
            [
                {ipAddress: '1.2.3.4', type: 'TPLINK'}
            ]
    },
    other: "something important"
};

Towage answered 19/4, 2023 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.