[typescript + createAsyncThunk()] What's the suggested approach for 'dynamic' typing? #1636
Replies: 3 comments
-
BTW, this is just an abstracted conceptual example, in my real case, |
Beta Was this translation helpful? Give feedback.
-
As for your first approach: without an outer closure you won't be able to specify your As for the second: it's probably not becoming a lot shorter than this.
Not really, it's just a little less readable in the devtools. We essentially do the same in RTK Query. Generally: if this is just fetching logic, you might also be interested to look into RTK Query? https://redux-toolkit.js.org/rtk-query/overview |
Beta Was this translation helpful? Give feedback.
-
@phryneas Thanks for the hint. Not sure if I explained and understood this correctly, but:
kinda like overloads for I haven't test, but I believe there shouldn't be any trouble to go with approach 1 with JavaScript, it's just kinda trade off with TS given current type definition for RTK?
I don't quite understand this. Did you mean it's actually the correct way to go with, or, it's not worth doing it?
How do you handle the Approach 2 is already working, it's just that a full set of thunks/reducers would be needed for each animal (and I have many animals), provided matching utilities would save some for reducers for sure, but still, they look really repetitive, although very clear...
Yes, that's on my list, looks interesting! I'm new to TS and RTK, rewriting a side-project (written in JS and traditional redux pattern) with TS and RTK, trying to learn TS and RTK. Leaving RTK Query alone for now just to keep things limited. :) |
Beta Was this translation helpful? Give feedback.
-
This is not an issue but more of a question regarding understanding redux design philosophy (and so I did not ask on SF).
Say, I have a store slice for different animals:
A typical async thunk for creating new
dog
could be:This works great. The thing is, the one for creating new
cat
(and all other animals) are exactly the same, so I want to make it a little bit more flexible to avoid repeat codes.The first approach I tried, was to play with the type generic for
createAsyncThunk()
, where I tried to fit in an union to infer the animal to be created, something like this:This obviously won't work, because I can't define
K
anywhere for the generic... but you get the idea.The second approach I tried, is to create an async thunk factory, something like:
The second approach works fine, but still, feels kinda repetitive, and will add more work on the reducer part. I would definitely prefer more on
createAnimal('dog')
rather thancreateDog()
,createCat()
......Question:
Beta Was this translation helpful? Give feedback.
All reactions