user2976358 user2976358 - 1 year ago 320
TypeScript Question

Cloning a TypeScript Object

I have a typescript class

export class Restaurant {

constructor ( private id: string, private name: string ) {


public getId() : string {

public setId(_id : string) { = _id;

public getName () {

public setName ( _name:string ) { = _name;


I then have an instance of this class ( this is an example ):

restaurant:Restaurant = new Restaurant(1,"TestRest");

I then store this restaurant object in some sort of cache restaurant );

then later in my application I get the restaurant back

var restToEdit = cache.get( "1" );
restToEdit.setName( "NewName" );

But because of javascripts pass by reference on objects, the changes I make to restToEdit also get saved in the restaurant that is in the cache.

I basically want the restaurant in the cache to be a totally different instance to the restToEdit.

I have tried using jQuery.clone and extend, but it doesn't seem to work and I think this is because of it being a typescript object. Or will that not matter?

Any answers on how to clone this object would be appreciated


Answer Source

.clone() only clones DOM elements. In order to clone JavaScript objects try jQuery.extend. Something like this

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

Typescript transpiles to JavaScript. So, JavaScript way will work fine.


// Transpiled version of TypeScript
"use strict";
    var Restaurant = (function () {
        function Restaurant(id, name) {
   = id;
   = name;
        Restaurant.prototype.getId = function () {
        Restaurant.prototype.setId = function (_id) {
   = _id;
        Restaurant.prototype.getName = function () {
        Restaurant.prototype.setName = function (_name) {
   = _name;
        return Restaurant;

// Test Snippet
var r1 = new Restaurant(1, "A");
var r2 = jQuery.extend(true, {}, r1);


<script src=""></script>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download