Reactjs 类型脚本反应状态:元素隐式地具有一个';任何';因为类型';州';没有索引签名
我正在使用Typescript并在迷你项目中做出反应。我现在刚开始打字和学习 所以我有这个状态:Reactjs 类型脚本反应状态:元素隐式地具有一个';任何';因为类型';州';没有索引签名,reactjs,typescript,Reactjs,Typescript,我正在使用Typescript并在迷你项目中做出反应。我现在刚开始打字和学习 所以我有这个状态: type State = { field1: string, field2: string, field3: number, field4: string, } const SomeFields = ['field1', 'field3']; class SomeComponent extends React.PureComponent<Props, State> {
type State = {
field1: string,
field2: string,
field3: number,
field4: string,
}
const SomeFields = ['field1', 'field3'];
class SomeComponent extends React.PureComponent<Props, State> {
state: State = {
// Default value for above fields
}
isValid = () {
SomeFields.every((key) => {
return this.state[key].length;
});
}
}
类型状态={
字段1:字符串,
字段2:字符串,
字段3:数字,
字段4:字符串,
}
常量SomeFields=['field1','field3'];
类SomeComponent扩展了React.PureComponent{
状态:状态={
//以上字段的默认值
}
isValid=(){
SomeFields.every((键)=>{
返回此.state[key].length;
});
}
}
在这里,此行this.state[key].length
抛出错误元素隐式具有“any”类型,因为类型“state”没有索引签名
我可以理解需要为SomeFields
定义类型,但我如何才能做到这一点?您必须隐式地告诉TypeScript这是状态键的数组
const SomeFields:数组
这也改善了TS体验,因为当您尝试将元素添加到SomeFields
或使用switch
等时,您将在编辑器/IDE中完成代码。const SomeFields:Array
@MU谢谢,这解决了上述错误,但给出了此错误类型错误:对象可能为“null”。
。可能是因为某些键在状态中为null
或具有false
值。我认为可能的null与状态有关