I'm 'simply' trying to clone an instance in typescript.
jQuery.extend(true, {}, instance)
doesn't work because methods are not copied
any help is greatly appreciated
You can have a generic clone function if your classes have a default constructor:
function clone<T>(instance: T): T {
const copy = new (instance.constructor as { new (): T })();
Object.assign(copy, instance);
return copy;
}
For example:
class A {
private _num: number;
private _str: string;
get num() {
return this._num;
}
set num(value: number) {
this._num = value;
}
get str() {
return this._str;
}
set str(value: string) {
this._str = value;
}
}
let a = new A();
a.num = 3;
a.str = "string";
let b = clone(a);
console.log(b.num); // 3
console.log(b.str); // "string"
(code in playground)
If your classes are more complicated (have other class instances as members and/or don't have a default constructor) then add a clone
method in your classes which knows how to construct and assign values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With