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
相关产品推荐
相关产品推荐

