如何在 TypeScript 中输入 Redux 状态以创建没有项目的新状态 [英] How to type Redux state in TypeScript to create new state without item

查看:38
本文介绍了如何在 TypeScript 中输入 Redux 状态以创建没有项目的新状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 TypeScript 2.x 和 Redux.我有一个接收动作的减速器,基于它我希望创建一个没有像这样的项目的新状态:

I'm using TypeScript 2.x and Redux. I have a reducer which receives an action, based on which I wish to create a new state without some item like this:

export function reducer(state = {}, action) {
  switch (action.type) {
    case SOME_ACTION:      
      let newState : { something: string } = state;
      delete newState.something;
      return newState;
    default:
      return state;
  }
}

感谢@basarat,我找到了删除东西的基础知识(见TypeScript 2:从 2 字段对象中删除项目).上面的代码基于该建议,但现在我得到了

Thanks to @basarat I figured out the basics of deleting things ( see TypeScript 2: Remove item from 2-field object). The code above is based on that advice, but now I instead get

    TS2322: Type '{}' is not assignable to type '{ something: string; }'.
  Property 'something' is missing in type '{}'. 

据我所知,这意味着我需要以某种方式推断传入状态的类型以删除此项目.

As far as I understand this means that I need to somehow infer the type of the incoming state to delete this item.

输入 Redux 状态的最佳方法是什么?或者有没有替代我的方法?

What's the best approach to type the Redux state? Or is there an alternative to my approach?

推荐答案

不要用 redux 做 mutating state.例如.以下不是一个好主意

Don't do mutating state with redux. E.g. the following is not a good idea

delete newState.something;

而是创建一个没有该道具的新对象,例如

Instead create a new object without that prop e.g.

const {something, ...newState} = state;
return newState;

除此之外,您还需要注释 state.为了快速破解,您可以简单地any:

Beyond that you need to annotate state. For a quick hack you can simply any:

export function reducer(state:any = {}, action) {

但是如果你仍然感到困惑,你应该阅读做一个更好的注释:https://basarat.gitbooks.io/typescript/docs/types/type-system.html

But you should read on doing a better annotation if you are still confused : https://basarat.gitbooks.io/typescript/docs/types/type-system.html

这篇关于如何在 TypeScript 中输入 Redux 状态以创建没有项目的新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆