Is there a way to efficiently duplicate a TypeScript class without losing getters and ensuring that nested classes and array items have new references?
I have attempted using JSON.parse(JSON.stringify(obj));
, but this method does not copy the getters. On the other hand, Object.assign(target, source);
successfully copies the getters, but the array items retain their original references.
Below is the structure of the 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>;
}