如何为现有React Context模块创建d.ts类型定义?
解决混合JS/TS项目中React Context的类型声明问题
问题核心
你之前的全局类型声明写法无效,是因为FormContext是从form.js模块导出的变量,并非全局类型,全局声明type FormContext无法关联到模块导出的实际变量上。
正确的d.ts写法
在项目中创建与form.js同目录的form.d.ts文件,内容如下:
import type React from 'react'; // 定义Context的属性类型 type FormContextProps = { register: (param: { fieldName: string; defaultValue: any; required?: boolean }) => void, onChange: (fieldName: string, value: any) => void, }; // 扩展form.js模块的类型声明 declare module './form' { export const FormContext: React.Context<FormContextProps>; }
注意:
./form要和你在TSX中导入FormContext时的路径完全一致,比如导入路径是import { FormContext } from '@/components/form',这里就写declare module '@/components/form'。
验证用法
现在在TSX文件中正常导入使用即可,无需手动断言类型:
import { FormContext } from './form'; const formContext = React.useContext(FormContext); // 此时formContext会自动识别为FormContextProps类型,不再报错 formContext.register({ fieldName: 'username', defaultValue: '' }); formContext.onChange('username', 'newValue');
补充说明
如果form.js还导出了其他变量,也可以在这个d.ts文件里一并声明对应类型,保持模块类型的完整性。
内容的提问来源于stack exchange,提问作者Vania Oliveira
相关产品推荐
相关产品推荐

