Home > Net >  How to adjust the overlap code in TypeScript
How to adjust the overlap code in TypeScript

Time:09-20

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';
}

CodePudding user response:

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
}
  • Related