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

TypeScript中类型引用生效但JSDoc未显示的问题排查

问题原因与解决方案

这是因为TypeScript在处理索引访问类型(即thisfile['testFunction']这类写法)时,不会自动保留原始接口成员上的JSDoc注释。虽然类型检查逻辑能正确识别该类型的约束(所以修改返回值类型会触发错误),但编辑器的语言服务不会把接口里的注释关联到通过索引访问得到的类型引用上。

解决方法

最简洁且维护性高的方式是用类型别名封装索引访问的类型,这样注释会被完整保留:

interface thisfile {
    /**
     * A test function to demonstrate this issue
     */
    testFunction: () => string     // 1
}

// 用类型别名封装索引访问类型
type TestFunc = thisfile['testFunction'];

const testFunction: TestFunc = () => {   // 2 现在悬停能看到JSDoc了
    return 'hello'
}

export default {
    testFunction   // 3
} as thisfile

也可以直接把JSDoc复制到变量定义上,但这种方式会造成注释冗余,后期修改接口注释时还要同步更新,不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:42:33