Safe JSON clone
Calling JSON.serialize
and then JSON.parse
on a value is the fastest general-purpose way to deeply clone an object in Javascript. However, the downside is that it only works on values for which x => JSON.parse(JSON.serialize(x))
is the identity function. In other words, this function will only work correctly on strings, numbers, booleans, null
, undefined
, and arrays and objects built off of these types.
It's common to choose a function name or leave comments warning about this constraint. However, in Typescript we can enforce this constraint at the type level using a recursive type:
Now, when passing any value that will not be transparently cloned via this function, Typescript will emit an error.
Last updated