【发布时间】:2019-01-05 02:05:45
【问题描述】:
我有以下接口:
interface AppState {
readonly grid : IGridSettings;
readonly selected : ISelectedSettings;
}
interface IGridSettings {
readonly extents : number;
readonly isXY : boolean;
readonly isXZ : boolean;
readonly isYZ : boolean;
readonly spacing : number;
}
interface ISelectedSettings {
readonly bodyColor : number;
readonly colorGlow : number;
readonly lineColor : number;
readonly selection : number[] | undefined;
}
interface Action<T = any> {
type: T
}
interface SetPropertyValueAction<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]> extends Action {
type : string;
payload : {
property : [KAction, KActionProp];
value : IUserActions[KAction][KActionProp];
};
}
最终,当发出 setPropertyValue 函数时,我的 redux reducer 会被调用:
const setPropertyValue = <KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>( property : [KAction, KActionProp], value : AppState[KAction][KActionProp] ) : SetPropertyValueAction<KAction, KActionProp> => ( {
type: 'SET_PROPERTY_VALUE',
payload: {
property,
value,
}
} );
function myReducer( state : AppState = INITIAL_STATE, a : Action ) : AppState {
switch( a.type ) {
case 'SET_PROPERTY_VALUE': {
const action = a as SetPropertyValueAction; // <- error here
return createNewState( state, action.payload.property, action.payload.value );
}
}
return states;
}
我遇到的问题是我不知道如何修复从 Action 到 SetPropertyValueAction 的转换。 TypeScript 告诉我错误是:
Generic type 'SetPropertyValueAction<KAction, KActionProp>' requires 2 type argument(s).
我尝试将出现错误的代码行更改为以下内容:
const action = a as SetPropertyValueAction<KAction extends keyof AppState, KActionProp extends keyof AppState[KAction]>;
...但这给了我两个错误,说“找不到名称 KAction 和 KActionProp”
如何将 Action 对象转换为通用 SetPropertyValueAction ??
这是我在此处回答的另一个问题的后续问题:How to add TypeScript type safety to my redux action?
【问题讨论】:
-
你可以关注这篇文章:medium.com/@martin_hotell/…
标签: typescript redux casting type-safety