简体   繁体   中英

How can I Destructure or optimize the typescript code?

In my typescript class I have skip function. In my interface I have mentioned data coming from backend.

On the front end I would like to rename the backend variable as shown below. There are multiple variables, how can I optimize the code ?

I thought of using Destructuring concept but not sure how to use. I need help

 this.recordId = data?.data1;
   this.oldValue = data?.data2;
    this.newValue = data?.data3;
     ............// many more

ts function

skip(rec: ABC) {
  const {  data1, data2, data3 } = rec;

  this.records.skip({ data1, data2, data3}).subscribe(data => {
    this.recordId = data?.data1;         ---------------------------->Here
    this.oldValue = data?.data2;         ---------------------------->
    this.newValue = data?.data3;         ---------------------------->
     ............// many more

    this.processIncomingRecord(data);
  });
}

rec.ts

export interface ABC {
    data1: number;
    data2: number;
    data3: number;
    }

Something like this might help. You can create a secondary "helper" map object (here MapABCToDEF ) that maps the keys from ABC to what their frontend key names will be. Then, you can construct your frontend type (illustrated here as DEF ) by using the " mapped types " feature (TS 4.1 and above).

interface ABC {
    data1: number;
    data2: number;
    data3: number;
}

const MapABCToDEF: {[Property in keyof ABC]: string} = {
    data1: 'recordId',
    data2: 'oldValue',
    data3: 'newValue'
}

type DEF = {
    [Property in keyof typeof MapABCToDEF as typeof MapABCToDEF[Property]]: ABC[Property];
}

在此处输入图像描述

This will help give you better type information is places you might want it. Ideally though you would just make your data names consistently the same across frontend and backend. Ie don't use data1 on the backend and recordId on the frontend, that will cause unnecessary complexity and confusion. Just pick one or the other and standardize it everywhere.

For the renaming itself, the map object MapABCToDEF can help you streamline the process of assigning key/values to this in a way that is consistent and type-enforced:

const abc: ABC = {
    data1: 100,
    data2: 200,
    data3: 300
}

// ...

const keys = Object.keys(abc) as Array<keyof typeof abc>;
keys.forEach(eaKey => {
    this[MapABCToDEF[eaKey]] = abc[eaKey];
});

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