'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)
Solution 1:[1]
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"}
Solution 2:[2]
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];
Solution 3:[3]
To clone an Array or Object :
Clone an Array :
const clonedArray = Object.assign([], myArray);
Clone an object :
const clonedObject = Object.assign({}, myObject);
Solution 4:[4]
const object: CustomType = {customkey: "customValue"}
const cloneObject = {...object} as CustomType;
This should work for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nitzan Tomer |
| Solution 2 | |
| Solution 3 | abahet |
| Solution 4 | sandesh bafna |
