简体   繁体   中英

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.

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'}. 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 . In the second case, you told the compiler it is number , so the compiler throws away the information about 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.

Please see the TypeScript code examples in the createApi documentation for information on which types you actually need to write. Essentially: all you need to type is your initialState and case reducer action function arguments. Nothing else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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