typecript cast/assertion with for循环
问题描述:
我正在循环访问数组中的数据,并希望将我的循环项目投射到扩展接口(它有一个额外的标签字段)。我可以重铸什么?到“PersonLabel”?typecript cast/assertion with for循环
for (const person of people) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
我试过的方法,如本(不编译):
for (const person:PersonLabel of people) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
,这(不编译)
for (const person of people) {
person = typeof PersonLabel;
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
答
你可以尝试:
for (const person of people as PersonLabel[]) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
答
您可以使用<Type>
或as Type
。
在你的情况,这意味着:
person = <PersonLabel> person;
或as
的首选方式:
person = person as PersonLabel;
记住更改const person
到let person
因为你不能重新分配const
。
或者你也可以在已经投它的循环是这样的:
for (const person of people as PersonLabel[]) { //<PersonLabel[] people should work as well...
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
这是假设PersonLabel
从类派生Person
。否则你不能施放类型(就像你不能投number
到string
)。