Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cloning a class instance in typescript

Tags:

typescript

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

like image 260
Friedrich Roell Avatar asked Mar 11 '17 13:03

Friedrich Roell


1 Answers

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.

like image 124
Nitzan Tomer Avatar answered Sep 28 '22 07:09

Nitzan Tomer