React TypeScript项目.tsx文件dispatch隐式any及索引签名报错如何解决
问题1:dispatch参数隐式any类型修复
你需要给dispatch参数明确标注类型,可根据你使用的Redux版本选择对应方案:
- 如果使用Redux Toolkit:
- 先在全局store配置文件(通常为
store.ts)中导出AppDispatch类型:
import { configureStore } from '@reduxjs/toolkit' export const store = configureStore({ reducer: { /* 你的业务reducer配置 */ } }) export type AppDispatch = typeof store.dispatch- 回到
auth.tsx导入类型后给dispatch标注:
import type { AppDispatch } from '你的store文件相对路径' // 给dispatch加类型标注 export const facebookAuthenticate = (state:string, code:string) => async (dispatch: AppDispatch) => { // 原有业务逻辑保持不变 } - 先在全局store配置文件(通常为
- 如果使用原生Redux:
从redux包导入Dispatch类型,结合你提前定义的登录相关action类型联合标注即可:import type { Dispatch } from 'redux' import type { AuthAction } from '你的action类型定义文件路径' export const facebookAuthenticate = (state:string, code:string) => async (dispatch: Dispatch<AuthAction>) => { // 原有业务逻辑保持不变 }
问题2:ts(7053)索引类型报错修复
该报错是因为Object.keys(details)返回值类型为string[],而details对象仅显式声明了state、code两个合法键,没有配置任意字符串索引签名,所以用字符串类型的key访问对象属性会触发类型校验失败。两种修复方案可选:
方案1:给key添加类型断言
直接在访问属性时将key断言为details的合法键类型,改动最小:
const formBody = Object.keys(details).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(details[key as keyof typeof details]) ).join('&');
方案2:给details声明索引签名
定义details时提前声明支持任意字符串类型的键,适合后续可能扩展details字段的场景:
const details: Record<string, string> = { 'state': state, 'code': code };
额外注意:你当前代码中axios.post的参数存在逻辑错误,post方法的第二个参数为请求体,第三个参数才是请求配置,你现在将formBody拼到了url的query参数中,没有正确传递请求体,符合规范的写法为:
const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/o/facebook/`, formBody, config);
内容的提问来源于stack exchange,提问作者Yusuf Doğan
相关产品推荐
相关产品推荐

