Reactjs 如何使用useReducer安全地编写类型动态属性设置器操作? 类型状态={ str:字符串; num:数字; }; 类型动作= |{type:'SET';属性:P;值:State[P]}; const reducer=(状态:状态,操作:操作)=>{ 开关(动作类型){ 案例“集合”: 返回{…state[action.property]:action.value}; } } let state:state={str:'',num:0}; state=reducer(state,{type:'SET',property:'str',value:10}); state=reducer(state,{type:'SET',property:'num',value:'nan'}); console.log(状态);//=>{str:10,num:'nan'}
我预期会出现类型错误,但实际设置的类型值不正确Reactjs 如何使用useReducer安全地编写类型动态属性设置器操作? 类型状态={ str:字符串; num:数字; }; 类型动作= |{type:'SET';属性:P;值:State[P]}; const reducer=(状态:状态,操作:操作)=>{ 开关(动作类型){ 案例“集合”: 返回{…state[action.property]:action.value}; } } let state:state={str:'',num:0}; state=reducer(state,{type:'SET',property:'str',value:10}); state=reducer(state,{type:'SET',property:'num',value:'nan'}); console.log(状态);//=>{str:10,num:'nan'},reactjs,typescript,Reactjs,Typescript,我预期会出现类型错误,但实际设置的类型值不正确 我该怎么办?对不起,我自己解决了。类型Action={[P in keyof State]:{type:'SET';属性:P;值:State[P]}[keyof State];欢迎提出建议。 type State = { str: string; num: number; }; type Action<P extends keyof State = keyof State> = | { type: 'SET';
我该怎么办?对不起,我自己解决了。类型Action={[P in keyof State]:{type:'SET';属性:P;值:State[P]}[keyof State];欢迎提出建议。
type State = {
str: string;
num: number;
};
type Action<P extends keyof State = keyof State> =
| { type: 'SET'; property: P; value: State[P] };
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'SET':
return { ...state, [action.property]: action.value };
}
}
let state: State = { str: '', num: 0 };
state = reducer(state, { type: 'SET', property: 'str', value: 10});
state = reducer(state, { type: 'SET', property: 'num', value: 'nan'});
console.log(state); // => { str: 10, num: 'nan' }