如何配置TypeScript以识别使用代码中已有的JSDoc类型标注?
问题现象
已为函数编写标注参数、返回值类型的JSDoc注释,TypeScript仍将对应参数判定为any类型,抛出错误:参数“isOpen”隐式具有“any”类型.ts(7006)(对应原英文报错:Parameter 'isOpen' implicitly has an 'any' type.ts(7006)),对应复现代码:
/** * Creates arrow icon's class name to rotate it upon its x axis. * * Arrow icon communicates to the user that they can expand or collapse the filter. * * @param {boolean} isOpen If the filter is open so that it can be viewed. * @returns {string} The class name for the arrow icon. */ const arrowClassName = (isOpen) => isOpen ? styles.arrowIcon : `${styles.arrowIcon} ${styles.expanded}`;

根因说明
TypeScript默认不会主动读取.js文件内的JSDoc类型标注做类型推导,只有开启对应配置后,才会基于JSDoc注释完成类型校验。如果是.ts后缀的文件,TypeScript优先识别原生TS类型语法,不会解析JSDoc内的类型定义。
解决方法
- 全局配置生效:在项目根目录创建/修改
tsconfig.json(TS项目)或jsconfig.json(纯JS项目),添加以下配置:
{ "compilerOptions": { "allowJs": true, // 允许对JS文件做类型处理 "checkJs": true, // 开启JS文件的类型检查,自动解析JSDoc类型 "noImplicitAny": true, // 禁止隐式any,和当前报错规则匹配 "skipLibCheck": false }, "include": ["src/**/*"] // 确保业务代码路径被纳入检查范围 }
- 单文件临时生效:如果不想全局开启JS类型检查,只需要在写了JSDoc的JS文件最顶部添加
// @ts-check注释,即可让TS对当前文件启用JSDoc类型解析,修改后代码如下:
// @ts-check /** * Creates arrow icon's class name to rotate it upon its x axis. * * Arrow icon communicates to the user that they can expand or collapse the filter. * * @param {boolean} isOpen If the filter is open so that it can be viewed. * @returns {string} The class name for the arrow icon. */ const arrowClassName = (isOpen) => isOpen ? styles.arrowIcon : `${styles.arrowIcon} ${styles.expanded}`;
- 注意:如果当前文件是.ts后缀,不要依赖JSDoc做类型标注,TypeScript对.ts文件不会解析JSDoc中的类型定义,直接使用TS原生类型语法定义参数和返回值即可:
const arrowClassName = (isOpen: boolean): string => isOpen ? styles.arrowIcon : `${styles.arrowIcon} ${styles.expanded}`;
- 配置缓存处理:修改配置后如果仍不生效,按快捷键
Ctrl+Shift+P(macOS为Cmd+Shift+P)调出VS Code命令面板,执行TypeScript: Restart TS Server重启TS服务,加载最新配置。
内容的提问来源于stack exchange,提问作者Steven K Inouye
相关产品推荐
相关产品推荐

