每当我将reducer传递给redux的createStore
时,某个地方的编译器会尝试分配GenericAction :> MyAction
,我猜,它应该执行相反的MyAction :> GenericAction
。我有什么遗失的吗?
编辑:strictFunctionTypes : false
禁用错误,因此与方差相关。
是否有解决方法而没有停用strictFunctionTypes
?
我在下面做了一个简化的例子。
//test helpers
function _typ<T>(): T {
return undefined as any
}
function _tryAssign<X extends Y, Y>(): any {}
//redux stub
type GenericAction = { type: string; [k: string]: any }
type Reducer<S> = (state: S, action: GenericAction) => S
type StoreCreator = <S>(reducer: Reducer<S>) => any
///my code
const createStore = _typ<StoreCreator>()
const initialState = { a: 1 }
type State = typeof initialState
type MyActions = {
type: "A1"
payload: {
pl1: string
}
}
const reducer = (state: State, actions: MyActions) => state
// Type 'Action' is not assignable to type 'MyActions'.
createStore(reducer)
// Type 'Action' is not assignable to type 'MyActions'.
_tryAssign<typeof reducer, Reducer<any>>()
//MyActions is assignable to Action
_tryAssign<MyActions, GenericAction>()
//Action is not assignable to MyActions
_tryAssign<GenericAction, MyActions>()
答案 0 :(得分:0)
https://github.com/piotrwitek/react-redux-typescript-guide建议使用redux ^ 4.0,或者如果使用redux 3.x则启用strictFunctionTypes : false
。