1

How can I copy/clone a typescript class? The parent class contains a nested class and also a collection of the nested class. Each type of class contains a getter. I would like if the copied class did not lose the getters, and the nested class and the array items have a new reference.

My problems are, the JSON.parse(JSON.stringify( obj )); not copied the getters. and the Object.assign(target, soure); copied the getters, but the array items keep the original references.

Here is the structure of classes

export interface IClassA {
  code: number;
  description: string;
}

export class ClassA implements IClassA {
  code: number;
  description: string;
  get descrAndCode() {
    return 'Getter A ' + this.description + ':' + this.code;
  }
}

export interface IClassB {
  name: string;
  code: number;
  classList: Array<ClassA>;
}

export class ClassB implements IClassB {
  name: string;
  code: number;
  get codeAndName(): string {
    return 'Getter B' + this.code + ':' + this.name;
  }
  nested: ClassA;
  classList: Array<ClassA>;  
}

1 Answer 1

1

Another way you deep copy of the object with getter & setter using follwing lodash clonedeep() method

import * as cloneDeep from 'lodash/cloneDeep';
...
let foo = cloneDeep(bar);

Hope this will help!

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for your answer, but I would not want to use external libs.
This library already available in your angular. You don't need installed this one
I tried it, it works. But I not saw when included the lodash into Angular. What was the first version which contains it?
What will happen if we create a project without CLI, the project will contain it? And if we make a production build in that case we should include it into package.json, am I right?
by default it required to all angular application. without this library your angular project won't work. so no worries you can use it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.