在typescript中加载类属性
我创建了一个“load”函数,它将采用JSON格式的数据,并将属性加载到我的类的属性中。我第一次尝试使用typescript,并且已经设法修复了大多数错误,但是有一些我无法解决在typescript中加载类属性,typescript,Typescript,我创建了一个“load”函数,它将采用JSON格式的数据,并将属性加载到我的类的属性中。我第一次尝试使用typescript,并且已经设法修复了大多数错误,但是有一些我无法解决 load(id): void{ let item:object = this.items.find(item => item.id == id); if(typeof(item) != 'undefined'){ for(let k in item){ if(item.hasOwnPro
load(id): void{
let item:object = this.items.find(item => item.id == id);
if(typeof(item) != 'undefined'){
for(let k in item){
if(item.hasOwnProperty(k)){
this[k] = item[k];
}
}
}
}
这会产生以下错误:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
No index signature with a parameter of type 'string' was found on type '{}'.
386 | for(let k in item){
387 | if(item.hasOwnProperty(k)){
> 388 | this[k] = item[k];
| ^
389 | }
390 | }
391 | }
我该如何着手解决这个问题?我使用的模式有问题,还是我可以用不同的方式声明类型来阻止错误出现?typeobject
(我承认这很令人困惑),没有索引签名,这意味着你不能用括号访问器读取或写入值
您可以通过声明let item:any
来解决此问题,但这将关闭任何类型检查
或者类似这样的让item:{[propName:string]:any}
这并不是更好