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

TypeScript + React 中如何定义封装useContext的自定义Hook返回类型

TypeScript 封装useContext自定义Hook返回类型解决方案

规范写法(推荐)

首先你需要在创建CorporateContext时就显式定义好对应的上下文类型,示例如下:

// 1. 先定义上下文的类型接口
interface ICorporateContext {
  // 此处替换为你实际上下文内的属性、方法类型,示例如下
  companyId: string;
  companyInfo: Record<string, any>;
  updateCompanyInfo: (info: Partial<Record<string, any>>) => void;
}

// 2. 创建Context时传入泛型指定类型
const CorporateContext = createContext<ICorporateContext>({} as ICorporateContext);

之后你的自定义Hook直接将返回类型指定为上述定义的接口即可,修改后的代码如下:

export const useCorporateContext = (): ICorporateContext => {
    return useContext(CorporateContext);
};

快捷写法(无需单独抽类型)

如果你不想额外定义上下文类型,可以直接使用TypeScript内置的工具类推导返回类型,写法如下:

export const useCorporateContext = (): React.ContextType<typeof CorporateContext> => {
    return useContext(CorporateContext);
};

注意事项

  • 不要使用any作为返回类型,会丢失类型校验能力和代码提示,违反TypeScript的类型安全设计
  • 如果你的TSlint规则没有强制要求函数显式声明返回类型,也可以直接省略返回类型声明,TS会自动推导useContext的返回值类型,同样可以消除警告

内容的提问来源于stack exchange,提问作者Denis2310

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:45:04