【问题标题】:"Imperatively" assign a predefined @callback signature to a function definition?“必须”将预定义的@callback 签名分配给函数定义?
【发布时间】:2021-06-09 19:16:24
【问题描述】:

如果我在 JSDoc 中使用 @callback 或在 .t.ds 库中使用 type 定义了函数签名,我可以使用 JSDoc 以某种方式将该签名“附加”到多个函数定义吗?

/**
 * @callback ruleDefiner
 * @param {RuleDefinitionBuilder} builder
 */

然后:

/** @thisFunctionIsA {ruleDefiner} */
function spellfix(builder) {

    // The IDE should know that builder is a RuleDefinitionBuilder
    const {depends, produces, cmd, T} = builder;

    const input = depends("foo.txt");
    const output = produces("foo.spellfixed.txt");
    cmd(T`spellfix ${input} > ${output}`);
}

/** @thisFunctionIsA {ruleDefiner} */
function sign(builder) {

    // The IDE should know that builder is a RuleDefinitionBuilder
    const {depends, produces, cmd, T} = builder;

    const input = depends("foo.spellfixed.txt");
    const output = produces("foo.signed.txt");
    cmd(T`sign ${input} > ${output}`);
}

我应该用什么来代替伪 JSDoc @thisFunctionIsA

【问题讨论】:

    标签: jsdoc


    【解决方案1】:

    是的,你可以,使用 @type 标签。

    /**
     * @callback ruleDefiner
     * @param {RuleDefinitionBuilder} builder
     */
    
    /** @type {ruleDefiner} */
    function spellfix(builder) {
    
        // The IDE should know that builder is a RuleDefinitionBuilder
        const {depends, produces, cmd, T} = builder;
    
        const input = depends("foo.txt");
        const output = produces("foo.spellfixed.txt");
        cmd(T`spellfix ${input} > ${output}`);
    }
    
    /** @type {ruleDefiner} */
    function sign(builder) {
    
        // The IDE should know that builder is a RuleDefinitionBuilder
        const {depends, produces, cmd, T} = builder;
    
        const input = depends("foo.spellfixed.txt");
        const output = produces("foo.signed.txt");
        cmd(T`sign ${input} > ${output}`);
    }
    

    编辑: 如果这确实/严格适用于 JSDoc,请参阅this JSDoc documentation 了解更多信息。但是,如果您像我一样,只在编辑器中将 JSDoc 与 JavaScript 用于 IntelliSense,您可能需要 this TypeScript documentation(JavaScript IntelliSense 实际使用的)。

    【讨论】:

    • 至少在 JetBrains IDE 中,使用 @type 并不像您想象的那样工作。它只是指定函数的返回类型。我已将其报告为错误,但似乎该报告陷入了困境,我也没有得到确认这确实是一个错误(只是他们可以重现它,这与承认它是一个错误不同) ),他们也没有说这是设计使然,我应该使用不同的语法。
    • 我基本上是在尝试为基于 JS 的 DSL 获取智能感知,其中 DSL 文件无法导入 DSL 类型或类。 DSL 文件只能默认导出一个入口点函数,该函数接收一个对象,通过该函数完成所有工作,我需要 IDE 知道该对象的类型。这种模式还有其他嵌套实例,其函数采用多个参数。
    • 由于我没有使用 JetBrains 的经验(我使用 VSC),我只能推测如何处理它。 @type 绝不意味着指定返回类型,当然不是在 JSDoc 或 TypeScript 中。如果问题确实出在@type 而不是其他问题上,那么我认为您能做的只有这么多,但我有几个想法:
    • 在黑暗中拍摄,也许问题更多在于@callback,您可以将整个函数定义替换为/** @typedef {(builder: RuleDefinitionBuilder) => any } ruleDefiner */,然后按预期使用@type {ruleDefiner}
    • 事实上 ruleDefiner 现在在 .t.ds 中定义,但我之前遇到过与 @callback 相同的问题。我基本上把“脚本宿主”移植到了TS,但是“用户脚本”必须保留在JS中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    相关资源
    最近更新 更多