带有for循环的打字稿/断言

时间:2017-09-06 12:39:10

标签: typescript casting type-assertion

我循环遍历数组中的数据,并希望将我的循环项目转换为扩展接口(它有一个额外的标签字段)。我能改装什么呢?到了#34; PersonLabel"?

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);
}

2 个答案:

答案 0 :(得分:0)

你可以尝试:

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

答案 1 :(得分:0)

您可以使用<Type>as Type

在你的情况下,这意味着:

person = <PersonLabel> person;

或使用as的首选方式:

person = person as PersonLabel;

请记住将const person更改为let person,因为您无法重新分配const

或者您可以在for循环中将其强制转换为:

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)。

相关问题