0

Suppose I have a Typescript class like the following:

class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

I create an instance of the class:

const myInstance = new MyClass(true, 'hi', 45);

If I want to copy the values of only the properties x and z to another object, I could do the following:

const myInstance = new MyClass(true, 'hi', 45);
const { x, z } = myInstance;
const myObject = { x, z };

Is there any better (and simple) way of achieving this?

Or is this the simplest way?

Note, the above example class is small. Imagine if the class has, say, 20 properties, and I want to get only 5 of them.

It would be good to see a generic solution to the problem.

Antony
  • 2,490
  • 1
  • 23
  • 35
  • The answers in the other question are applicable here although they would need some type annotations/assertions to appease the TypeScript compiler. Do any of those answers work for you? – jcalz Feb 14 '20 at 16:40
  • 1
    @jcalz, thank you for pointing out the other question, looks like the top answers there are more along the lines of Andrew Nolan's answer (https://stackoverflow.com/a/60230061/3559967). So I will go with his answer. – Antony Feb 14 '20 at 17:20

3 Answers3

1

You can try something like this:

class MyClass {
  constructor(public x: boolean, public y: string, public z: number) {}
}

const myInstance = new MyClass(true, 'hi', 45);

const { y, ...xAndZ } = myInstance;

console.log(xAndZ) // outputs => {x: true, z:45}
Andrew Nolan
  • 1,665
  • 2
  • 16
  • 19
  • Thank you, this looks good, however, if the class grows with more properties, then we have to add more variables. For example, `{ y, z, a, b, ...theRest}`. Any other ideas? – Antony Feb 14 '20 at 16:35
0

Just pass the values you need:

const myInstance = new MyClass(true, 'hi', 45);
const myObject = { x: myInstance.x, z: myInstance.z };
Fernando Bravo Diaz
  • 148
  • 1
  • 3
  • 10
  • Thank you, this is fine, however, if the class grows with more properties and if we need more properties to copy, then the object declaration also grows. Any other ideas? – Antony Feb 14 '20 at 16:34
  • 2
    Andrew Nolan's answer seems to be the more appropriate in case you need pass a lot of properties, the downside is that it leaves you with declared variables that may go unused. – Fernando Bravo Diaz Feb 14 '20 at 16:36
  • Yep, agreed with @FernandoBravoDiaz. This can be a maintenance headache if the variable count increases. At which point you will need an adapter/converter of sorts for ease of use. – Andrew Nolan Feb 14 '20 at 19:27
0

If this is a one-off copy, then I suggest just doing what Fernando Bravo Diaz suggests. If this is something you need to do often, then you want to employ an adapter:

function someAdapter(someObj: MyClass): NewObj {
    return {
        x: someObj.x,
        z: someObj.z
    }
}
ehutchllew
  • 785
  • 6
  • 13