如何为带连字符的第三方库react-social-sharing本地声明TS类型
1. 修正tsconfig.json配置
别纠结typeRoots了,直接用include把自定义类型文件夹纳入编译范围更靠谱,paths在这里完全没必要,删掉多余配置:
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "moduleResolution": "Node", "esModuleInterop": true, "skipLibCheck": true, "strict": true }, "include": [ "src/**/*", "local-types/**/*" // 必须包含自定义类型文件夹 ] }
2. 正确编写本地类型声明文件
带连字符的模块名必须用带引号的declare module语法,别用namespace或者不带引号的模块声明。在local-types/react-social-sharing/index.d.ts里这么写:
import type { FC, ReactNode } from "react"; // 先定义组件通用Props,根据react-social-sharing的实际API补充 export interface SocialShareComponentProps { url: string; title?: string; description?: string; children?: ReactNode; style?: React.CSSProperties; size?: number; } // 匹配完整的包名,连字符直接写在引号里 declare module "react-social-sharing" { // 导出库中实际存在的组件,比如Facebook、Twitter等 export const Facebook: FC<SocialShareComponentProps>; export const Twitter: FC<SocialShareComponentProps>; export const LinkedIn: FC<SocialShareComponentProps>; export const Pinterest: FC<SocialShareComponentProps>; // 其他组件按需补充 }
3. 排查常见坑
- 别用
namespace,ES模块场景下declare module "包名"才是正确的声明方式 - 写完后重启TS服务器(VSCode按Ctrl+Shift+P搜"Restart TS Server"),缓存会导致类型不生效
- 确保
local-types的目录结构正确:local-types/react-social-sharing/index.d.ts,对应包名的文件夹名要和包名一致 - 如果库有默认导出,就在
declare module里加export default ...,但react-social-sharing一般是命名导出组件
内容的提问来源于stack exchange,提问作者avenmia
相关产品推荐
相关产品推荐

