JSDoc for reused Function interface

╄→尐↘猪︶ㄣ 提交于 2019-12-08 01:13:56

问题


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...

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?

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


回答1:


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
 */

You can then use sendEmail as a type:

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

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) { ... }

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.



来源:https://stackoverflow.com/questions/55086068/jsdoc-for-reused-function-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!