You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将函数的JSDoc转发至对象字面量导出的外部变量?

解决JSDoc注释从内部函数转发到外部对象属性的问题

要在不移动原有函数JSDoc的前提下,让外部作用域的变量继承内部函数的注释,可通过以下几种JSDoc技巧实现,确保VSCode悬停时能显示完整注释:

方法1:使用@type关联内部函数类型

在返回的对象字面量属性上,用@type {typeof 内部函数名}标注,让编辑器识别该属性与内部函数的类型关联,从而继承注释:

const { printRandom } = (() => {
    /**
     * Prints a random number
     */
    const printRandom = () => console.log(Math.random())

    return {
        /** @type {typeof printRandom} */
        printRandom
    }
})()

这样外部解构得到的printRandom变量,悬停时会直接显示内部函数的JSDoc注释,无需修改原有注释位置。

方法2:使用@inheritDoc继承文档

通过@inheritDoc指令,让对象属性直接继承内部函数的文档注释:

const { printRandom } = (() => {
    /**
     * Prints a random number
     */
    const printRandom = () => console.log(Math.random())

    return {
        /** @inheritDoc printRandom */
        printRandom
    }
})()

此方法明确指定继承目标函数的文档,编辑器会自动拉取对应注释内容。

方法3:提前定义函数类型(适用于复杂场景)

如果需要复用函数类型定义,可先通过@typedef定义带注释的函数类型,再让内部函数和对象属性都关联该类型:

const { printRandom } = (() => {
    /**
     * @typedef {function()} PrintRandomFn
     * @description Prints a random number
     */

    /** @type {PrintRandomFn} */
    const printRandom = () => console.log(Math.random())

    return {
        /** @type {PrintRandomFn} */
        printRandom
    }
})()

这种方式适合多个地方需要复用同一函数类型和注释的场景,保持注释的一致性。

以上三种方法都无需移动原有函数的JSDoc注释,仅通过在返回对象属性上添加简短的JSDoc指令,即可实现注释的转发,满足VSCode悬停时显示完整注释的需求。

内容的提问来源于stack exchange,提问作者user20416

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:51:12