繁体   English   中英

Typescript Redux Action Generic with Iterable Type

[英]Typescript Redux Action Generic with Iterable Type

已解决:如果您遇到这个确切的问题,请不要犯我的愚蠢错误。 当我应该刚刚通过 object 时,我试图在Object.assign中解构 object。 @Eldar@Akxe非常友好地对代码进行了重新审视,并帮助我在评论中看到了我的错误。


问题:我正在尝试为 typescript 中的 redux 操作创建一个可重用的实体,因此我可以在减速器中传递一个类型,但它抱怨我的类型不可迭代,我不知道如何解决这个问题。 我盲目地尝试添加typeofIterable无济于事,所以我正在寻找一些帮助和解释。

我的用户有一个实体:

export default interface UserEntity {
  uid: string | null;
  firstName: string | null;
}

并为我的操作创建了一个通用实体:

export default interface StoreAction<T> {
  payload: T;
  type: string;
}

在我的减速器中,我希望像这样实现它:

const initialState: UserEntity = {
  uid: null,
  firstName: null,
};
export default (state = initialState, action: StoreAction<UserEntity>) => {
  switch (action.type) {
    case 'Some string':
      return Object.assign({}, state, ...action.payload); // Warning that action.payload is not iterable
    default:
      return state;
  }
};

但是 VS Code 抱怨Type 'UserEntity' must have a '[Symbol.iterator]()' method that returns an iterator. 虽然我了解它在抱怨什么,但我不知道如何解决它。

如果这里不明显,我想在这个UserEntity的结构中传递我的操作 json 的有效负载,然后能够使用扩展运算符将它与我的 redux Z9ED39E2EA931586B6A985A6942EF57 合并。 我希望将其设为通用,因为某些操作将具有 arrays,有些可能只是 boolean 等。redux 站点给出了类似的示例,显示扩展运算符显然缺少某些接口,但矿。

编辑:添加我的 tsconfig.json:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "commonjs",
    "lib": [
      "es6"
    ],
    "allowJs": true,
    "jsx": "react-native",
    "noEmit": true,
    "isolatedModules": true,
    "strict": true,
    "moduleResolution": "node",
    "baseUrl": "./",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true
  },
  "exclude": [
    "node_modules",
    "babel.config.js",
    "metro.config.js",
    "jest.config.js"
  ]
}

Object.assign({}, state, ...action.payload)实际上是一个无效的语法。 关于如何修复它,您有两种选择。

Either pass the object to the Object.assign as-is: return Object.assign({}, state, action.payload)

,或使用解构,因为它做同样的事情但可能提供更好的性能(对于某些引擎) return {...state, ...action.payload }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM