【问题标题】:How to describe a function returning an array consists of 3 elements of different types如何描述返回数组的函数由 3 个不同类型的元素组成
【发布时间】:2020-11-07 17:54:40
【问题描述】:

我正在编写一个中间件辅助函数,它返回一个包含 3 个元素的数组:

  1. ServerIncomingMessage
  2. ServerResponse 或 null
  3. 总是Function

辅助函数是这样的:

function getCallbackParts(args) {
    return [
        args[0],
        args.length === 3 ? args[1] : null,
        args.length === 3 ? args[2] : args[1]
    ];
}

所以,稍后在代码中,我会这样做:

function MyMiddleware() {
    const [request, response, next] = getCallbackParts(arguments);

    request.transportType = request.hasOwnProperty('rooms') ? 'socket.io' : 'http';

    next();
}

我执行代码没有问题,但我需要记录 getCallbackParts 返回的结果,所以我的 IDE(我使用 WebStorm)会自动将 request 视为 ServerIncomingMessage

我试过这个(变体 1,产生相同结果的合并变体):

/**
 * @return [Server|IncomingMessage, ServerResponse|null, Function]
 * @return [(Server|IncomingMessage), (ServerResponse|null), Function]
 * @return {[Server|IncomingMessage, ServerResponse|null, Function]}
 * @return {[(Server|IncomingMessage), (ServerResponse|null), Function]}
 */

但是这样我的 IDE 显示 request 可以是 ServerIncomingMessageServerResponsenullFunctionresponsenext 也是如此。

我也试过这个(变体 2,合并了两个产生相同结果的变体):

/**
 * @return {Array<(Server|IncomingMessage), (ServerResponse|null), Function>}
 * @return {Array.<(Server|IncomingMessage), (ServerResponse|null), Function>}
 */

这样,request 被正确检测到,但responsenext 也由于某种原因继承了Server|IncomingMessage 类型。

这种情况下如何编写正确的jsDoc返回类型?

【问题讨论】:

    标签: javascript webstorm jsdoc


    【解决方案1】:

    尝试用括号分组。

    /**
     * @return {[(Server|IncomingMessage), (ServerResponse|null), Function]}
     */
    

    【讨论】:

    • 我也试过这个(并在我的问题中更新了“变体 1”以显示我在尝试什么)。这样IDE显示请求可以是ServerIncomingMessageServerResponsenullFunction
    【解决方案2】:

    这样解决了:

    /**
     * @return {{0: Server|IncomingMessage, 1: ServerResponse|null, 2: Function}}
     */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2017-02-10
      • 2019-10-04
      • 2011-02-14
      • 1970-01-01
      • 2017-05-26
      相关资源
      最近更新 更多