Deep clone in TypeScript (preserving types) Deep clone in TypeScript (preserving types) typescript typescript

Deep clone in TypeScript (preserving types)


Typescript isn't discarding type information here. In the DefinitelyTyped lodash.d.ts file, you can see that cloneDeep is defined as

cloneDeep<T>(    val: T,    customizer?: (value: any) => any,    thisArg?: any) : T

Ignoring the arguments we don't care about, it takes a T as input, and spits out a T as output. So Typescript isn't losing any type information; it considers the output of cloneDeep to be the same type as the input.

You should be able to verify this via your editor: assuming you have some editor that lets you inspect the type of variables or autocompletes methods (which I'd highly recommend, if you don't).


Why then is the typeof not working as you expect? It's because the Typescript type information doesn't carry over to runtime. instanceof is a native JS operator, which Typescript doesn't change the behavior of, which you can see by running this snippet:

"use strict";class A {}let a = new A();let b = _.cloneDeep(a);if (b instanceof A) {  alert("b is an instance of A");} else {  alert("b is not an instance of A");}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js"></script>