我注意到在Type脚本中使用useState时出现了意外的行为,它允许分配任何属性,即使该属性不存在于接口中.例如:
interface ComponentState {
foo: string,
bar: boolean
}
const [state, setState] = useState<ComponentState>({ foo: 'foo', bar: false });
const onAction = () => {
setState((prevState) => {
...prevState,
bar: true,
help: 'why is this allowed?'
});
}
为什么TypeScrip没有抱怨"Help"属性?如果我试图将bar(布尔值)设置为字符串,它将会出错.
这与PrevState对象传播有关吗?
我不喜欢这样,因为它允许错误通过.我是不是遗漏了什么?我查看了useState的定义,但我不认为它允许[key: string]: any