我可以在不丢失类型检查的情况下迭代属性列表吗?

时间:2019-08-16 11:00:57

标签: typescript

考虑以下简单代码:

applySelectedOrganization(apiData) {
  this.formFields.producer.fullName = apiData.fullName;
  this.formFields.producer.kpp = apiData.kpp;
  this.formFields.producer.inn = apiData.inn;
  this.formFields.producer.ogrn = apiData.ogrn;
  this.formFields.producer.shortName = apiData.shortName;
  //# missing fields? address x2, site; phone?
}

如果this.formFields实现了一个接口,则此代码将进行类型检查,如果我添加了

  this.formFields.producer.unexisting = apiData.some;

我会被警告。

但是,上面的代码太冗长了(在某些情况下,可能会比仅复制(例如对每个道具进行验证等)更复杂的东西),我会将其重写为

applySelectedOrganization(apiData) {
  for(let prop of ['fullName', 'kpp', 'inn', 'ogrn', 'shortName'])
    this.formFields.producer[prop] = apiData[prop];
  //# missing fields? address x2, site; phone?
}

但是在那种情况下,我会丢失类型检查。

我可以以某种方式重写循环(或以其他任何形式迭代prop名称),以便不会丢失编译时类型检查吗?

1 个答案:

答案 0 :(得分:1)

您可以首先遍历apiData,然后检查每个属性以确保它存在于Producer接口上。

export interface Producer {
    fullName: string;
    kpp: string;
    inn: string;
    ogrn: string;
    shortName: string;
    [propName: string]: any;
}

export interface ApiData {
    [propName: string]: any;
}

export interface Form {
    producer: Producer;
}


function applySelectedOrganization(form: Form, apiData: ApiData) {
  for (let prop in apiData) {
      if (prop in formFields.producer) {
          form.producer[prop] = apiData[prop];
      } else {
          console.log(`Warning: invalid property ${prop}.`)
      }
  }
}

const data = {
    "fullName": "Mel Brooks",
    "inn": "123",
    "ogrn": "Brooksfilms",
    "shortName": "Mel",
    "random_prop": "should show warning"
};

let formFields: Form = {
    producer: {fullName: '', kpp: '', inn: '', ogrn: '', shortName: ''}
};

applySelectedOrganization(formFields, data);
console.log(JSON.stringify(formFields, null, 2));

输出

Warning: invalid property random_prop.

{
  "producer": {
    "fullName": "Mel Brooks",
    "kpp": "",
    "inn": "123",
    "ogrn": "Brooksfilms",
    "shortName": "Mel"
  }
}