Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript interface variable clone

I know the interface of the typescript is a Type, so if I define an interface, I can use it to define a variable. My question is that, is there any (pre-defined) method to copy a variable of an interface? for example:

interface Person {
  name: string;
  birthday: string;
}
let person: Person = <Person>{};
person.name = "bob";
person.birthday = "19000909";
console.dir(person);
let copyPerson: Person = <Person>{};
copyPerson = person;
copyPerson.name = "Alice";
//then the person's name is also Alice. because the reference of person is passed to copyPerson.

after I change the copyPerson, the person will change too. I know I can just assign the every property of the person to the copyPerson, but is there any method to make a separate copy of person? (By the way, if it is class, I can new an object)

like image 204
Xin Meng Avatar asked Aug 27 '26 22:08

Xin Meng


2 Answers

You can use Object.assign:

let copyPerson = Object.assign({}, person);
copyPerson.name = "Alice";

console.log(person); // {name: "bob", birthday: "19000909"}
console.log(copyPerson); //  {name: "Alice", birthday: "19000909"}
like image 190
Nitzan Tomer Avatar answered Aug 29 '26 16:08

Nitzan Tomer


Just had kinda the same issue so I'll post what I've found to help the other in my case:

If your object contains sub-object. When you use Object.asign() the sub-objects references will be copied and you will end up with the same problem but only with the sub-objects.

So you have to use another Object.assign() for each sub-object, but after using Object.assign() on the parent object since it will copy reference.

And you can also use this method to clone objects and sub Object:

let originalObject = 
{
    a:'a', 
    b:'b', 
    subObj:
    {
        c:'c',
        d:'d',
    },
};
//clone object
let cloneObject = {...originalObject};
//clone sub object
cloneObject.subObj = {...originalObject.subObj};
//now modification on cloneObject and its sub-object won't occure in originalObject

The spread operator can also be used with array:

let clonedArray = [...originalArray];

like image 28
WisePlatypus Avatar answered Aug 29 '26 17:08

WisePlatypus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!