combineReducers doesn't infer type

前端 未结 2 1894
伪装坚强ぢ
伪装坚强ぢ 2021-01-15 05:27

I am using combineReducersin my React TypeScript app:

// combinedReducer.ts
import { combineReducers } from \'redux\'
import reducer1 from \'./r         


        
相关标签:
2条回答
  • 2021-01-15 06:03

    Ensure that Redux is at version 4.0.0 or higher. The type mappings for combineReducers was released with version 4.0.0, here's the related PR on the redux github.

    You can update your package.json file:

    ...
    "dependencies": {
       "redux": "^4.0.3"
    }
    ...
    

    Then run npm install to update to the latest version.

    Once you've made this change, make sure you restart your IDE to reload the type mappings.

    0 讨论(0)
  • 2021-01-15 06:06

    Same problem for me using redux 4.0.5 and typescript 4.0.1. Had to write a inferrer myself:

    type BaseReducerMap<S> = {
        [K in keyof S]: (state: S[K], action: any) => S
    }
    
    export type InferRootState<ReducerMap extends BaseReducerMap<S>, S = any> = {
        [K in keyof ReducerMap]: ReturnType<ReducerMap[K]>
    }
    

    Then for your set of reducers (before you combine them)

    const reducers = {
        login: loginReducer,
        chatUsers: chatUsersReducer,
    };
    const combinedReducer = combineReducers(reducers);
    
    export type State = InferRootState<typeof reducers>;
    

    Then typescript can successfully infer the type of my State. I don't know why it fails in this version.

    0 讨论(0)
提交回复
热议问题