Почему я не могу просто так набрать свой редуктор, не добавив "| undefined" к моему типу состояния редукса?
const reducer: Reducer<ReduxState> = function(state: ReduxState, action: any) ...
Дополнительный контекст ::::
Это работает нормально:
export const reducer: Reducer<ReduxState | undefined> = function (
state: ReduxState | undefined,
action: any
) {
return state
}
export default reducer
Однако это не происходит при удалении параметра состояния "undefined" из fxn:
export const reducer: Reducer<ReduxState | undefined> = function (
state: ReduxState,
action: any
) {
return state
}
export default reducer
, который дает ошибку:
Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState | undefined, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'ReduxState | undefined' is not assignable to type 'ReduxState'.
Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)
или это:
export const reducer: Reducer<ReduxState> = function (
state: ReduxState | undefined,
action: any
) {
return state
}
export default reducer
, который дает сообщение об ошибке:
Type '(state: ReduxState | undefined, action: any) => ReduxState | undefined' is not assignable to type 'Reducer<ReduxState, AnyAction>'.
Type 'ReduxState | undefined' is not assignable to type 'ReduxState'.
Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)
И, наконец, это также не работает:
import {ReduxState, ReduxAction, ReduxActionType} from './types'
import {Reducer} from 'redux'
export const reducer: Reducer<ReduxState> = function (
state: ReduxState,
action: any
) {
return state
}
export default reducer
с ошибкой сообщения:
Type '(state: ReduxState, action: any) => ReduxState' is not assignable to type 'Reducer<ReduxState, AnyAction>'.
Types of parameters 'state' and 'state' are incompatible.
Type 'ReduxState | undefined' is not assignable to type 'ReduxState'.
Type 'undefined' is not assignable to type 'ReduxState'.ts(2322)
TL;DR: Typescript не в восторге от моего Reducer, если я специально не разрешу тип "ReduxState | undefined" в Reducer<ReduxState|undefined>
и function(state: ReduxState | undefined)
.