使用react-file-viewer组件遇TS类型声明缺失问题求助
解决react-file-viewer的TypeScript声明缺失问题
1. 先明确:官方类型包不存在
@types/react-file-viewer这个包目前并未发布,所以提示里让你安装它的方案根本走不通,别在这浪费时间,直接用手动声明类型的方式。
2. 修正声明文件的笔误
你看到的错误提示里有个低级笔误:declare module 'react-file-viewe'; 最后少了个字母r,这也是你手动声明后没生效的核心原因之一。按以下步骤来:
- 在项目的
src目录下新建types文件夹(没有就创建) - 在
types里新建react-file-viewer.d.ts文件 - 把下面的代码粘进去:
declare module 'react-file-viewer' { import React from 'react'; interface FileViewerProps { fileType: string; filePath: string; onError?: (error: Error) => void; errorComponent?: React.ReactNode; [key: string]: any; // 兼容组件可能带的其他未明确的props } export const FileViewer: React.FC<FileViewerProps>; }
3. 让TypeScript识别你的声明文件
打开tsconfig.json,确保配置里包含了这个声明文件的路径:
{ "compilerOptions": { "typeRoots": ["./node_modules/@types", "./src/types"] }, "include": ["src/**/*", "src/types/**/*"] }
4. 应急方案:临时跳过类型检查
如果上面的步骤都没解决,你可以在导入时加注释临时绕过类型检查(不推荐长期用,只是应急):
// @ts-ignore import { FileViewer } from 'react-file-viewer';
内容的提问来源于stack exchange,提问作者Kunagisa Tomo
相关产品推荐
相关产品推荐

