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

TypeScript环境下创建带setter的React Context遇TS编译错误求助

解决React Context中TypeScript类型错误问题

直接按以下步骤修改代码即可解决两个问题:

  1. 定义Context的类型接口
    先明确Context的结构类型,让TypeScript能正确推断每个属性的类型:

    interface ErrorContextType {
      error: string;
      setError: (val: string) => void;
    }
    
  2. 传入符合类型的默认值
    默认值里的setError用下划线_标记未使用的参数,消除"val未使用"的警告:

    const Context = createContext<ErrorContextType>({
      error: "",
      setError: (_val: string) => {}
    });
    

这样修改后:

  • TypeScript会识别setError需要接收一个string参数,不会再提示"Expected 0 arguments, but got 1";
  • 用_val替代val,明确表示这个参数是故意不使用的,消除未使用参数的警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 03:42:39