如何为 `pipe`d ES6 函数生成 JSDoc

How to generate JSDoc for `pipe`d ES6 function

我有一个 ES6 风格的函数,它是使用 asyncPipe 的函数组合定义的。

import { getItemAsync } from 'expo-secure-store';

const asyncPipe = (...fns) => x => fns.reduce(async (y, f) => f(await y), x);

const getToken = () => getItemAsync('token');

const liftedGetToken = async ({ ...rest }) => ({
  token: await getToken(),
  ...rest,
});

const liftedFetch = ({ body, route, token, method = 'GET' } = {}) =>
  fetch(route, {
    ...(body && { body: JSON.stringify(body) }),
    headers: {
      'Content-Type': 'application/json',
      ...(token && { Authorization: `Bearer ${token}` }),
    },
    method,
  });

const json = res => res.json();

/**
 * @method
 * @param {Object} fetchSettings the settings for the fetch request
 * @param {Object} fetchSettings.body the body of the request
 * @param {string} fetchSettings.route the URL of the request
 * @param {string} fetchSettings.method the method of the request
 * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
 */
const request = asyncPipe(liftedGetToken, liftedFetch, json);

如您所见,我尝试向其添加 JSDoc 描述。但是当我在任何地方使用它时,我的编辑器 VSCode 不会建议它的参数。你如何用 JSDoc 声明这些类型的函数?我如何获得此函数的参数以与 Intellisense 一起使用?

VSCode会尝试显示asyncPipe里面匿名函数的注释。如果您在其中添加 JSDoc 注释,您可以看到行为:

const asyncPipe = (...fns) =>
  /**
   * My asyncPipe description
   * @param {Object} x Any object
   */
  x => fns.reduce(async (y, f) => f(await y), x);

const request = asyncPipe(liftedGetToken, liftedFetch, json);

不幸的是,JSDoc 无法像您尝试的那样覆盖匿名函数的文档。但是,您可以像这样强制您的意图 VSCode,请注意,这会引入一个额外的函数调用:

const doRequest = asyncPipe(liftedGetToken, liftedFetch, json);

/**
 * @method
 * @param {Object} fetchSettings the settings for the fetch request
 * @param {Object} fetchSettings.body the body of the request
 * @param {string} fetchSettings.route the URL of the request
 * @param {string} fetchSettings.method the method of the request
 * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
 */
const request = fetchSettings => doRequest(fetchSettings);

VSCode 在底层使用 TypeScript 引擎,它不擅长从函数组合中推断类型,而且如您所见,它不能将无点组合识别为函数声明。

如果您需要类型提示,您可以通过在其周围包装一个指向函数来指定组合函数的参数。

我会这样写 - 注意:默认值使 JSDoc 不需要类型提示,但无论如何您可能希望保留 JSDoc 用于描述。还要确保由默认值回退引起的故障会产生足够的错误消息。

/**
  * http request with JSON parsing and token management.
  * @param {Object} fetchSettings the settings for the fetch request
  * @param {Object} fetchSettings.body the body of the request
  * @param {string} fetchSettings.route the URL of the request
  * @param {string} fetchSettings.method the method of the request
  * @param {string} fetchSettings.token should only be used for testing and unauthenticated requests
  */
const request = ({
  body = {},
  route = '',
  method = 'GET',
  token = ''
}) => asyncPipe(liftedGetToken, liftedFetch, json)({
  body, route, method, token
});