DEV Community

loading...

Discussion on: React Context with useReducer and Typescript.

Collapse
mannguyen0107 profile image
Man Nguyen

As it turned out your way of doing the combine reducers also works for type-safe all you gotta do is use type assertion ie:

const mainReducer = ({ products, shoppingCart }: InitialStateType, action: ProductActions | ShoppingCartActions) => ({
  products: productReducer(products, action as ProductActions),
  shoppingCart: shoppingCartReducer(shoppingCart, action as ShoppingCartActions),
});
Enter fullscreen mode Exit fullscreen mode

By using the 'as' keyword there you can now get rid of the unions type on the action arg of your reducers

Thread Thread
elisealcala profile image
Elizabeth Alcalá Author

Hey, you are right, type assertion works well in this case, it makes the code look cleaner without the union types.

Thanks a lot.