1. 13
    How to Apply Types to Redux Selectors
    59s

How to Apply Types to Redux Selectors

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

What I've found with nearly every method provided by RTK is that type support comes really easy. This is definitely true for the createSelector method. As long as you type the state argument on your input selectors, TypeScript can calculate your return value as well as the value of the various inputs to your result function.

if you want to type the function fully you can use the following syntax:

createSelector<RootState, ResultInputType(s)..., ResultOutputType>(...)
```

---

More info about types in Redux can be found here:
https://redux.js.org/recipes/usage-with-typescript

Jamund Ferguson: [0:00] If you're curious about how to type the createSelector() method, there is a way but I just want to show you that without doing very much other than identifying RootState, it already correctly identifies what items is, what products is and it knows that this is going to return a string.

[0:14] Over here in Cart.tsx, when I say const totalPrice, it already recognizes that totalPrice is a string and I didn't really have to do any typing except just these two initial RootState arguments.

[0:25] If you want to type createSelector explicitly, you can do it. Using the generic syntax, you can pass in the RootState as the first argument and then the appropriate types for the various arguments going into your final selector function. In this case, we're going to just use any, and any.

[0:40] The last argument would be the returned value, which here would be a string. With that, you can get rid of explicitly typing your first two functions. That's how you would explicitly type use selector, but in my experience, it works pretty well just to leave off the explicit typing and only worry about adding RootState to any of your initial selectors.

Steve
Steve
~ 3 years ago

I'm really confused about how the number 'total.toFixed' is getting cast to a string when it reaches 'totalPrice' in Cart.tsx?

Jamund Ferguson
Jamund Fergusoninstructor
~ 3 years ago

Every number in JavaScript has a toFixed method which returns a the number as a string with a set number of decimal places included. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed for a thorough explanation. Does that clear things up?

Markdown supported.
Become a member to join the discussionEnroll Today