简体   繁体   中英

How to adjust the overlap code in TypeScript

I created 2 new Objects in for loop, which they have almost similar value (Languague, PlantCode, CreationTime ). How could I adjust it better?

 for (let entry of data) {
  const objectA: Information = {
    language: 'de',
    statusCode: entry['ec_Status'].statusMain + ':' + entry['ec_Status'].statusAdditional,
    plantCode: entry['ec_ControlType'],
    creationTime: entry['creationTime'],
    type: 'status',
  };


  const objectB: Information = {
    language: 'de',
    statusCode: entry['ec_Status'].infoMain + ':' + entry['ec_Status'].infoAdditional,
    plantCode: entry['ec_ControlType'],
    creationTime: entry['creationTime'],
    type: 'information',
  };
  await this.deviceStatusInformationService.getStatustext(objectA);
  await this.deviceStatusInformationService.getStatustext(objectB);

and I defined Information like that:

export interface Information {
  plantCode: number;
  statusCode: string;
  language: string;
  text?: string;
  subtext?: string;
  creationTime: Date;
  type: 'status' | 'information';
}

I agree with the comment of @kikon, the is not much optimisation you can do, in your case you only have 2 objects so it makes no sense. But in case you would have 10 object or so the code would be more cleaner:

for (let entry of data) {
  const template: Information = {
    language: 'de',
    plantCode: entry['ec_ControlType'],
    creationTime: entry['creationTime'],
  } as Information;

  const objectA: Information = {
    ...template,
    statusCode: entry['ec_Status'].statusMain + ':' + entry['ec_Status'].statusAdditional,
    type: 'status',
  };


  const objectB: Information = {
    ...template,
    statusCode: entry['ec_Status'].infoMain + ':' + entry['ec_Status'].infoAdditional,
    type: 'information',
  };

  // your code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM