'Typescript - Custom type assignment by value [duplicate]
In one of my procedures I need to periodically reset a custom type, but I noticed that in TypeScript (and I think in JavaScript too maybe), when I assign a variable of a custom type to another variable of the same type, the assignment is made by reference and not by value.
For example this code:
type testing = {
a: string;
b: number;
};
let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };
console.log(v1);
console.log(v2);
v1 = v2;
v1.a = "Edited";
console.log(v1);
console.log(v2);
generates this output
{ a: 'one', b: 1 }
{ a: 'two', b: 2 }
{ a: 'Edited', b: 2 }
{ a: 'Edited', b: 2 }
Is there a way to assign it by value without assigning every property of the type?
(in my example I need my v2 variable to remain equals to { a: "two", b: 2 })
Solution 1:[1]
For simple cases like this, you can make use of the spread operator to create a shallow copy of an object.
type testing = {
a: string;
b: number;
};
let v1: testing = { a: "one", b: 1 };
let v2: testing = { a: "two", b: 2 };
console.log(v1);
console.log(v2);
// copy all of the top-level keys and values from v2
// into a new object and assign that to v1
v1 = { ...v2 };
v1.a = "Edited";
console.log(v1);
console.log(v2);
Note there are some caveats here. As indicated by the link in Tobias S' comment, this will only do a shallow copy. If you have more complex objects, this will cause issues.
let v1: testing = { a: "one", b: 1, c: { d: 1 } };
let v2: testing = { a: "two", b: 2, c: { d: 2 } };
v2 = { ...v1 };
// v1.c is the same object as v2.c because we only shallowly
// copied, so this assignment is reflected in both
v2.c.d = 60;
console.log(v1);
console.log(v2);
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 | CollinD |