【问题标题】:typescript casting / assertion with a for loop带有for循环的打字稿强制转换/断言
【发布时间】:2018-02-14 23:04:38
【问题描述】:

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

【问题讨论】:

    标签: typescript casting type-assertion


    【解决方案1】:

    你可以试试:

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

    【讨论】:

      【解决方案2】:

      您可以使用<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)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-02
        • 1970-01-01
        • 1970-01-01
        • 2018-08-31
        • 2022-06-20
        • 1970-01-01
        相关资源
        最近更新 更多