Cannot infer correct types in selectIds from getSelectors

Viewed 641

I have a simple redux store setup with createEntityAdapter. The initial state contains and entity, ids, status, error setup as such

const carouselEventAdapter = createEntityAdapter<CarouselEventStateInterface>()

const initialState = carouselEventAdapter.getInitialState({
  entities: { //some data here },
  ids: [1,2],
  status: 'idle',
  error: null,
})

const carouselEventSlice = createSlice({
  name: 'carouselEvent',
  initialState,
  reducers: {},
  extraReducers: {},
})

export const {
  selectIds,
  selectById,
} = carouselEventAdapter.getSelectors<RootState>( state => state.carouselEvent)

// export const {} = carouselEventSlice.actions

export default carouselEventSlice.reducer

When I try to call the selectIds function, it shows me the type as EntityId[] while I want number[] as the type for eventids

const eventids = useSelector(selectIds)

Could someone correct me on my types because I've tried to find answers to this everywhere and no luck

1 Answers

By including id: [1,2] in your initial state, the state type for the slice becomes ids: number[]. But the entity adapter just uses EntityId.

As a workaround, you can select the ids from the state directly without using getSelectors

const useSelector = createSelectorHook<RootState>();

const eventIds = useSelector(state => state.carouselEvent.ids );

This gets the type EntityId[] & number[] which is just number[].

Typescript Playground Link

Now you've got me wondering how hard it would be for the redux-toolkit types to support a generic <I extends EntityId = EntityId> here.

Related