JSDoc用于重用的Function接口 [英] JSDoc for reused Function interface

查看:189
本文介绍了JSDoc用于重用的Function接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要连接到多个电子邮件工具,并将其API抽象为一个通用的sendEmail函数,每个服务具有相同的params和相同的returns.这意味着对于每个电子邮件服务(Mailchimp,Sen​​dGrid ...),我必须编写一个具有相同JSDoc的函数,该函数描述相同的@params和相同的@returns ...

I'm connecting to multiple email tools and abstracting their APIs to one common sendEmail function with the same params and same returns for each service. That means that for every email service (Mailchimp, SendGrid...), I have to write a function which has an identical JSDoc describing the same @params and same @returns...

是否存在有效的JSDoc语法,以将@typedef或类似功能与Function配合使用,而不是在每个函数上方声明@params@returns,只需描述类型?

Is there a valid JSDoc syntax to use @typedef or similar with a Function, where instead of declaring @params and @returns above each function, just describe the type?

...未禁用ESLint的 require-jsdoc

...Bonus points for not disabling ESLint's require-jsdoc

推荐答案

有一种定义它的方法.使用 @callback 相当于功能的@typedef.

There is a way to define it. Use @callback which is the equivalent of @typedef for functions.

/**
 * @callback sendEmail
 * @param {string} to
 * @param {string} body
 * @returns {boolean} to indicate success or failure
 */

然后可以使用sendEmail作为类型:

You can then use sendEmail as a type:

/**
 * @param {sendEmail} sender - function to send the email
 */
function createEmailService(sender) { ... }

问题在于没有一种指定函数类型的好方法,因为函数上的@type被解释为函数的返回类型,而不是整个函数定义.因此,以下内容将无法正常工作.

The problem is there is not a good way to specify the type of a function because @type on a function is interpreted to be the return type of the function, not the entire function definition. So something like the following does not work.

/**
 * @type {sendEmail}
 */
function mailchimpEmailSender(to, body) { ... }

您可以使它与以下各项一起使用,但这不是一个很好的解决方案.我仍在寻找更好的解决方案.

You can get it to work with the following, but it is not a great solution. I am still looking for a better solution.

/**
 * @type {sendEmail}
 */
let mailchimpEmailSender
mailchimpEmailSender = function(to, body) { ... }

更新: 我发现,如果将函数声明包装在括号中,则似乎允许@type应用于变量而不是函数声明.

Update: I have figured out that if you wrap the function declaration in parens it seems to allow the @type to apply to the variable instead of the function declaration.

/**
 * @type {sendEmail}
 */
const mailchimpEmailSender = (function(to, body) { ... })

到目前为止,这是我最喜欢的解决方案,它允许您使用适当的变量声明关键字.唯一的缺点是它要求您记住添加并非严格必要的代码.

This is the solution I like best thus far as it allows you to use the appropriate variable declaration keyword. The only downside is it requires you to remember to add in code that is not strictly necessary.

这篇关于JSDoc用于重用的Function接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆