2017-09-06 52 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)。