19

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.

1

3 Answers 3

27

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>>.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.