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

React Context在TypeScript中类型被识别为any的问题求助

解决React Context类型被识别为any的问题

可能的原因及修复方案

  • 未安装React类型定义包
    确认已安装@types/react,未安装的话执行对应命令:

    # npm
    npm install @types/react --save-dev
    
    # yarn
    yarn add @types/react --dev
    
  • 检查tsconfig.json配置
    确保tsconfig.json的compilerOptions包含关键配置,开启严格模式能强化类型检查:

    {
      "compilerOptions": {
        "jsx": "react-jsx", // 根据React版本选择react/react-jsx/react-jsxdev
        "strict": true,
        "esModuleInterop": true
      }
    }
    
  • 显式指定变量类型
    给变量强制声明类型,避免TypeScript自动推断为any:

    type TestContextType = {
        test: number
    }
    
    const context: React.Context<TestContextType> = React.createContext<TestContextType>({
        test: 0
    })
    
    const used: TestContextType = React.useContext(context)
    
  • 匹配React与类型包版本
    确保@types/react的版本和项目中react的版本一致,版本不兼容会导致类型识别异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:22:01