简体   繁体   中英

can I define a JSDoc @return type based on the shape of a @param type?

let's say I have a set of functions which perform some processing on some data. they all take the same argument but return different datatypes:

import {
  getTotalValue,   // @type {function(DataObject):number}
  getIsComplete    // @type {function(DataObject):boolean}
} from './helpers';

const totalValue = getTotalValue(data); // @type {number}
const isComplete = getIsComplete(data);   // @type {boolean}

I would like to write a helper function which performs a set of transformations to this data and returns all their values at once:

const {
  totalValue,   // @type {number}
  isComplete    // @type {boolean}
} = applyTransformations({
  totalValue: getTotalValue, // @type {function(DataObject):number}
  isComplete: getIsComplete  // @type {function(DataObject):boolean}
});

is there a way in JSDoc to specify the relationship between the keys/values of the argument object and the keys/values of the return value object?

  /**
   * @param {???} transformationFunctions
   * @return {???} an object with the same keys as the param, and values the return values of each transformation function
   */
  function applyTransformations(transformationFunctions) {
    return Object.entries(transformationFunctions).reduce(
      (acc, [k,fn]) => ({ ...acc, [k]: fn(dataObject) }), {}
    );
  }

(the shape and number of the helper function's arguments and return values can change, if that would make the typing easier. this is new code and nothing is set in stone.)

Yes, you can actually. Using @template tag will do the magic here.

/**
 * @template T
 * @param {T} value
 * @returns {{ payload: T }}
 */
const createPayload = value => ({ payload: value });

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