Home > Enterprise >  JSON.parse(JSON.stringify(data)) type in typescript
JSON.parse(JSON.stringify(data)) type in typescript

Time:11-29

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.

Where I missed the type?

I tried to put type after variable declaration

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

CodePudding user response:

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[]; 

CodePudding user response:

You can also use the spread operator

const dataClone: DataType[] = [...state.initialData]

CodePudding user response:

mention your object structure as interface

interface Structure{
 foo: string
 bar: number
}

then mention the type as like this

const dataClone: Array<Structure> = data

I think this may help you.

  • Related