VS Code中TypeScript对象属性悬停/建议为何不显示类型文档注释?
问题描述
在VS Code中,定义带JSDoc注释的类型别名(如SpecialString)后,在接口属性、函数参数里引用该类型时,悬停或输入提示的类型信息弹窗不会显示该类型本身的注释;但直接为属性添加的注释能正常显示。同时TS Playground无法复现VS Code中的注释显示效果,模板字面量类型也存在相同问题。
用户希望无需重复为每个函数参数添加@param注释,就能直接复用类型本身的注释。示例代码如下:
/** * Special documented string to reuse this comment. */ type SpecialString = string; interface Options { /** Foo */ x: number; /** Bar */ y: number; s: SpecialString; // 此处s的提示不会显示SpecialString的注释 } const fn1 = (options: Options) => { console.log('foo'); }; // 调用fn1时,x/y的注释正常显示,但s的注释缺失 // fn1({}) // 不想给fn2、fn3的参数重复写相同的@param注释 const fn2 = (special: SpecialString) => console.log(special); const fn3 = (special: SpecialString, x: number) => console.log('foo'); // 调用fn2时,参数special的提示缺失SpecialString的注释 // fn2(); interface SpecialStrings { /** Special comment */ special: string; } const fn4 = (special: SpecialStrings['special']) => console.log(special); // 调用fn4时,参数special的提示缺失原属性的注释 // fn4();
解决方案
目前TypeScript的IntelliSense默认不会自动将类型别名/接口属性的注释继承到引用它们的位置,以下是几种无需重复编写注释的解决办法:
方法1:用JSDoc
@typedef统一管理类型注释
将类型定义为JSDoc的@typedef,引用时通过@type或@param标签关联,注释只需写一次:/** * Special documented string to reuse this comment. * @typedef {string} SpecialString */ interface Options { /** Foo */ x: number; /** Bar */ y: number; /** @type {SpecialString} */ s: SpecialString; } /** * @param {SpecialString} special */ const fn2 = (special: SpecialString) => console.log(special);方法2:用接口包装实现注释复用+类型约束
用单属性接口包装需要复用注释的类型,既能继承注释,还能实现类型 branding(防止普通值混入):interface SpecialString { /** Special documented string to reuse this comment. */ __brand: string; } // 使用时通过类型断言转换 const myStr = "test" as unknown as SpecialString; interface Options { /** Foo */ x: number; /** Bar */ y: number; s: SpecialString; }方法3:升级TypeScript版本
部分较新的TypeScript版本对类型注释的继承支持有所优化,升级到最新稳定版可能解决部分场景下的注释不显示问题。
注:TS Playground与VS Code的表现差异,主要是因为两者使用的TypeScript服务版本不同,提示逻辑也略有区别。
内容的提问来源于stack exchange,提问作者Neil M
相关产品推荐
相关产品推荐

