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)
您可以使用<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 number
to一样string
)。
你可以尝试:
for (const person of people as PersonLabel[]) {
person.label = `${person.namespace}:${person.name}`;
this.peopleList.push(person);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8857 次 |
最近记录: |