Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript – Custom Type Assignment by value

In one of my procedures i need reset periodically 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);

generate this output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{ 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 do it without assign every property of the type?

(in my example i need my v2 variable to remain equals to { a: "two", b: 2 })

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading