【问题标题】:can I define a JSDoc @return type based on the shape of a @param type?我可以根据 @param 类型的形状定义 JSDoc @return 类型吗?
【发布时间】:2021-03-23 05:45:36
【问题描述】:

假设我有一组对某些数据执行某些处理的函数。它们都采用相同的参数,但返回不同的数据类型:

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}

我想编写一个辅助函数,它对该数据执行一组转换并立即返回它们的所有值:

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

JSDoc中有没有办法指定参数对象的键/值与返回值对象的键/值之间的关系?

  /**
   * @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) }), {}
    );
  }

(辅助函数的参数和返回值的形状和数量可以改变,如果这样可以使打字更容易。这是新代码,没有什么是一成不变的。)

【问题讨论】:

    标签: javascript types jsdoc


    【解决方案1】:

    是的,实际上可以。使用@template 标签将在这里发挥作用。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 2022-01-23
      相关资源
      最近更新 更多