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

JSON.parse(JSON.stringify(data)) type in typescript

I’m using typescript and want to deep copy my object.
I used JSON.parse(JSON.stringify(data)) method here is the code

const dataClone: DataType[] = JSON.parse( JSON.stringify(data) );

My data is an array with object which type is DataType[].
But I’m getting warning that I used any type and it is – Unsafe assignment of an any value.

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

Where I missed the type?

I tried to put type after variable declaration

const dataClone: DataType[] = JSON.parse( JSON.stringify(data) );

>Solution :

Your type is lost to string when you use JSON.stringify then to any when you use JSON.parse so you have to use a type assertion to tell the compiler it’s of type DataType[] like this:

const dataClone = JSON.parse(JSON.stringify(data)) as DataType[]; 
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