Javascript 尝试从具有枚举属性的历史对象中提取状态时遇到Typescript错误
我有一个枚举,看起来像Javascript 尝试从具有枚举属性的历史对象中提取状态时遇到Typescript错误,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我有一个枚举,看起来像 enum values { first, second, } const { first } = values; useEffect(() => { if (!state[first]) { // do something } }, []); 在我的组件中,我访问历史对象 const { push, location: { state = {} } } = useHistory(); 在同一个组件中,在auseffect中,我做了如下操
enum values {
first,
second,
}
const { first } = values;
useEffect(() => {
if (!state[first]) {
// do something
}
}, []);
在我的组件中,我访问历史对象
const { push, location: { state = {} } } = useHistory();
在同一个组件中,在auseffect
中,我做了如下操作:
enum values {
first,
second,
}
const { first } = values;
useEffect(() => {
if (!state[first]) {
// do something
}
}, []);
这抛出了错误
Element implicitly has an 'any' type because expression of type
'values.first' can't be used to index type '{}'.
Property '[values.first]' does not exist on type '{}'.ts
我做错了什么?我应该为状态编写自己的接口吗?问题就在这里
const { push, location: { state = {} } } = useHistory();
^
因为您在默认状态值为空对象({}
)的情况下解构。TS将把键和值推断为any
解决方案是通过将泛型类型参数传递给useHistory
调用,为LocationState
提供显式类型。对于您正在使用的枚举,类型可能如下所示
枚举值{
第一,
第二
}
类型TLocState={[输入值]:字符串/*值的所需类型*/}
常量{push,位置:{state}}=useHistory();
//某些值将被推断为字符串
const someVal=state[values.first]
请看一下我很高兴答案有用。