2017-09-06 51 views
1

我正在循环访问数组中的数据,并希望将我的循环项目投射到扩展接口(它有一个额外的标签字段)。我可以重铸什么?到“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); 
} 

回答

0

你可以尝试:

for (const person of people as PersonLabel[]) { 
    person.label = `${person.namespace}:${person.name}`; 
    this.peopleList.push(person); 
} 
0

您可以使用<Type>as Type

在你的情况,这意味着:

person = <PersonLabel> person; 

as的首选方式:

person = person as PersonLabel; 

记住更改const personlet 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。否则你不能施放类型(就像你不能投numberstring)。