使用 for 循环进行打字稿转换/断言

SD *_*Dev 8 casting type-assertion typescript

我正在循环数组中的数据,并希望将循环项目转换为扩展接口(它有一个额外的标签字段)。我可以重铸什么?到“个人标签”?

for (const person of people) {
    person.label = `${person.namespace}:${person.name}`;
    this.peopleList.push(person);
}
Run Code Online (Sandbox Code Playgroud)

我尝试过这样的方法(无法编译):

for (const person:PersonLabel of people) {
    person.label = `${person.namespace}:${person.name}`;
    this.peopleList.push(person);
}
Run Code Online (Sandbox Code Playgroud)

和这个(不编译)

for (const person of people) {
    person = typeof PersonLabel;
    person.label = `${person.namespace}:${person.name}`;
    this.peopleList.push(person);
}
Run Code Online (Sandbox Code Playgroud)

Wer*_*son 6

您可以使用<Type>as Type

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

person = <PersonLabel> person;
Run Code Online (Sandbox Code Playgroud)

或首选方式as

person = person as PersonLabel;
Run Code Online (Sandbox Code Playgroud)

请记住更改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);
}
Run Code Online (Sandbox Code Playgroud)

这假设PersonLabel派生自类Person。否则,您无法转换类型(就像无法转换 a numberto一样string)。


Tit*_*mir 1

你可以尝试:

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