You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为现有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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 02:25:02