使用扩展运算符或 Object.assign 将失去严格的 typescript 检查。
type State = {
key1: string;
key2: string;
};
function App() {
const [state, setState] = React.useState<State>({
key1: "",
key2: ""
});
React.useEffect(() => {
setState(prevState => {
return { ...prevState, ...{ key3: "" } };//no ts error
});
setState(prevState => {
return Object.assign({}, prevState, { key3: "" });//no ts error
});
setState({key1:'', key2:'', key3: ''});//ts error!!
}, []);
return <div>{JSON.stringify(state)}</div>;
}
我试过 Vanilla TS,还是有问题
type Person = {
name: string,
age: number
}
const person1:Person = {...{name: 'a', age: 20, salary: 20}};//no error
const person2:Person = Object.assign({name: 'a', age: 20, salary: 20});//no error
const person3:Person = {name: 'a', age: 20, salary: 20};//ts error
ts 似乎有一些错误。我想知道是否有一种简单的方法可以通过严格的类型检查来更新状态?谁能指导我解决这个问题?
最佳答案
是的,这似乎是 Typescript 社区中的一个已知问题。 Check this discussion on Github out
有一个解决方法。 可以找到对其的引用 here .
TLDR;
您基本上是在将两者合并形成一个新状态之前键入您的新状态。两个正确键入的状态将导致正确键入的状态。
看看这个片段:
(() => {
type State = { foo: string };
const state: State = { foo: 'bar' };
const assignedValues: State = { foo: 1 }; //complain expected
const newState: State = Object.assign({}, state, assignedValues)
})();
据此,我认为您的新代码应该是这样的:
const [state, setState] = React.useState<State>({
key1: "",
key2: ""
});
React.useEffect(() => {
setState(prevState => {
const valueToChange: Partial<State> = {
key1: "I am sure that this is typed",
}
return Object.assign({}, prevState, valueToChange);
});
}, []);
return <div>{JSON.stringify(state)}</div>;
关于javascript - 类型检查和扩展运算符 (setState),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56900354/