简体   繁体   English

如何使用 Typescript 和 Redux 工具包来发送一个动作?

[英]How to use Typescript with Redux Toolkit to dispatch an action?

I'm trying to use typescript inside my slices of redux toolkit, but when I try to call an action, I can't see the type of the payload.我正在尝试在 redux 工具包的切片中使用 typescript,但是当我尝试调用操作时,我看不到负载的类型。

This is a slice for example: enter image description here例如,这是一个切片:在此处输入图像描述

This is the store: enter image description here这是商店:在此处输入图片描述

And this is my problem, when I try to call the setFilters action I can put whatever I want as payload, for example {foo: 'hello'}.这是我的问题,当我尝试调用 setFilters 操作时,我可以将任何我想要的内容作为有效负载,例如 {foo: 'hello'}。 enter image description here enter image description here在此输入图片描述 在输入图片描述

I would like to have the payload locked with the correct interface.我想用正确的接口锁定有效负载。 Is it possible?是否可以?

Firstly: please post code, not screenshots.首先:请发布代码,而不是屏幕截图。 I will not give you code in the answer, because I would have to type it from your screenshots - that makes answering very hard.我不会在答案中给你代码,因为我必须从你的屏幕截图中输入它——这使得回答变得非常困难。

On to the question itself: your type annotations remove type information here.关于问题本身:您的类型注释在此处删除了类型信息。 Don't write so many annotations.不要写那么多注释。

For example:例如:

const foo = 5;
const bar: number = 5

In the first case, the compiler knows something is a number and also 5 .在第一种情况下,编译器知道 something 是一个number ,也是5 In the second case, you told the compiler it is number , so the compiler throws away the information about 5 .在第二种情况下,您告诉编译器它是number ,因此编译器丢弃了有关5的信息。

Your annotations of createSlice do the same - TS could infere most types from usage, but your manual annotations remove all that extra info and so TypeScript goes back to generic things that do not have details about payload etc.您对createSlice的注释做同样的事情 - TS 可以从使用中推断出大多数类型,但是您的手动注释删除了所有这些额外信息,因此 TypeScript 返回到没有关于有效载荷等详细信息的通用事物。

Please see the TypeScript code examples in the createApi documentation for information on which types you actually need to write.请参阅createApi 文档中的 TypeScript 代码示例,了解有关您实际需要编写哪些类型的信息。 Essentially: all you need to type is your initialState and case reducer action function arguments. Nothing else.本质上:您需要输入的只是您的initialState和 case reducer 操作 function arguments。没有别的。

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

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