TypeScript引入react-web-vector-icons报TS7016类型错误如何解决?
TS7016 类型报错解决方案
TS7016: Could not find a declaration file for module 'react-web-vector-icons'. '/Users/apple/Documents/GitHub/ProjectAliance/node_modules/react-web-vector-icons/dist/index.js' implicitly has an 'any' type.
Try npm i --save-dev @types/react-web-vector-icons if it exists or add a new declaration (.d.ts) file containing declare module 'react-web-vector-icons';
方案1:安装社区维护的类型包
直接执行报错提示的安装命令即可:npm i --save-dev @types/react-web-vector-icons如果该类型包存在,安装完成后重启TypeScript服务即可解决报错,同时可以获得完整的类型提示。
方案2:添加简易模块声明(无类型提示)
如果不存在对应的@types包,可自行添加声明文件:- 在项目src目录下新建
custom.d.ts文件(文件名可自定义,后缀必须为.d.ts) - 在文件中写入以下内容:
declare module 'react-web-vector-icons';- 确认
tsconfig.json中的include配置包含了该声明文件所在目录,例如配置为"include": ["src/**/*"]即可自动识别。
该方案会将该模块默认标记为any类型,可解决报错但不会提供代码补全、类型校验能力。
- 在项目src目录下新建
方案3:补全自定义类型声明(有完整类型提示)
如果需要完整的类型能力,可以在声明文件中补全库的导出类型,示例如下:declare module 'react-web-vector-icons' { import type { ComponentType } from 'react'; interface IconProps { name: string; size?: number; color?: string; // 其他你用到的属性 } export const Icon: ComponentType<IconProps>; // 补全其他导出的组件、方法类型 }不推荐的临时方案
可以修改tsconfig.json中的compilerOptions.noImplicitAny为false,关闭全局隐式any校验,但会影响整个项目的类型安全性,不建议使用。
内容的提问来源于stack exchange,提问作者Azeem Sarwar
相关产品推荐
相关产品推荐

