
Typescript Deep Clone Challenge
The Problem
Have you ever done something like this?
1type Student = { name: string, age: number, teacher: string };
2
3const roger: Student = { name: "Roger", age: 10, teacher: "Ms. Perry" };
4//sally is roger's twin sister and has the same teacher...
5const sally: Student = roger;
6sally.name = "Sally";
7
8//result...
9console.log(roger.name === sally.name); //???
The result is true
because after we assigned roger
to sally
, both variables are pointing to the same object. Unlike primitives, object variables point to a reference of the object.
Enter cloning...
What do you think about this revised version?
1type Student = { name: string, age: number, teacher: string };
2
3const roger: Student = { name: "Roger", age: 10, teacher: "Ms. Perry" };
4//sally is roger's twin sister and has the same teacher...
5const sally: Student = {...roger};
6sally.name = "Sally";
7
8//result...
9console.log(roger.name === sally.name); //???
Here, the result will be false
because we used the spread operator to make a new object. Thus, roger
and sally
point to different objects. This is known as a shallow copy (or clone) of the object.
Why is it called "shallow copy"?
"A shallow copy of an object is a copy whose properties share the same references (point to the same underlying values) as those of the source object from which the copy was made." (mdn)
In our case, all of the properties are primitives (string, number, boolean). But what if one (or more) of the properties was an object?
1type Name = { first: string, last: string };
2type Student = { name: Name, age: number, teacher: string };
3
4const roger: Student = {
5 name: { first: "Roger", last: "Jackson"},
6 age: 10, teacher: "Ms. Perry"
7};
8//sally is roger's twin sister and has the same teacher...
9const sally: Student = {...roger};
10sally.name.first = "Sally";
11
12//result...
13console.log(roger.name === sally.name); //???
Rats... we are back to true
. Both roger
's and sally
's name properties point to the same Name
object! In other words, the cloning (copying) was only at the first level and did not go deep into the object.
The Challenge
The challenge is for you to create a generic deepClone()
function that will take any value and return a deep copy of that value such that no references (to objects) are shared between the original and the clone.
There are two ways to approach this problem; one using serialization, and one building the copy from the original. Can you produce both solutions?
Our Answer
As always, we present our answer as one possibility among many, and certainly not offered as the best approach.