-1

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;
    }
Tejas Mehta
  • 281
  • 1
  • 4
  • 17
  • I'm not really sure that you have any good options here. If you want them renamed and added as members to the class, I think the best way is how you've done it, although I admit it's painfully verbose. – mhodges Apr 02 '21 at 05:34
  • 1
    I suppose you could use `Object.assign(this, {recordId: data1, oldValue: data2, newValue: data3})` but it doesn't save you that much typing – mhodges Apr 02 '21 at 05:44
  • Thanks @mhodges. I could not find any better solution yet – Tejas Mehta Apr 02 '21 at 05:46

1 Answers1

0

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

enter image description here

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. I.e. 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];
});
jered
  • 11,220
  • 2
  • 23
  • 34