combineReducers doesn't infer type

2020-04-18 06:18发布

问题:

I am using combineReducersin my React TypeScript app:

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

const combinedReducer = combineReducers({
    reducer1,
    reducer2,
})

export default combinedReducer

I understand from redux documentation that combineReducers should infer it's type based on the combined reducers.

However, for me it does not, even though each combined reducer has its return type recognised:

( ReturnType<typeof combidedReducer> is unknown)

What is wrong here?

Here are my maximally simplified reducers:

// reducer1.ts
const initialState: boolean = false

const reducer1 = (state = initialState): boolean => state

export default reducer1
// reducer2.ts
const initialState: boolean = false

const reducer2 = (state = initialState): boolean => state

export default reducer2

回答1:

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.