Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
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 - Fatal编程技术网

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' }