Skip to content
Advertisement

Is is possible to use an typescript Union type for the state of a Redux Toolkit Slice?

I’d like to use an union type like this to represent my slice’s state when using Redux Toolkit:

JavaScript

It seems like the usage of Immerjs in the reducer files prevents me from switching between the two Union options, e.g.:

JavaScript

Which gives me the following Typescript error:

JavaScript

Is there any way to make this work? My current workaround is not using an union type to represent the state but I’m wondering if there is a workaround. I have also tried not using booleans but string literals for the loading key but it produces the same error.

Advertisement

Answer

NOTE: Per the docs, Option 2 is the better approach.

Option 1. Provide the generic parameter types for createSlice.

JavaScript

The state type in case reducer:

enter image description here

Option 2. Cast the initial state. See Defining the Initial State Type

JavaScript

package versions:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement