12/08/2019, 09:03
Simple ways to deep copy an object in Typescript
interface Iperson { firstName: string, lastName: string, fullName: string, age: number, sex: string } const userA = { firstName: 'Nguyen', lastName: 'Luan' } // shallow copy const userAA: Iperson = <Iperson>userA; console.log(userA === userAA) // true console.log(userAA) / ...
interface Iperson { firstName: string, lastName: string, fullName: string, age: number, sex: string } const userA = { firstName: 'Nguyen', lastName: 'Luan' } // shallow copy const userAA: Iperson = <Iperson>userA; console.log(userA === userAA) // true console.log(userAA) // 1 Object.assign(target, ...source) const userB: Iperson = Object.assign( <Iperson>{}, userA ); console.log(userA === userB) // false userB.sex = 'male'; console.log(userB) // 2 Spread Operator const userC: Iperson = <Iperson>{ ...userA } console.log(userC === userA) // false userC.fullName = 'Nguyen Thieu Luan'; console.log(userC) // 3 JSON.stringtify() and JSON.parse() const userD: Iperson = JSON.parse(JSON.stringify(userA)); console.log(userD === userA); // false userD.age = 18; console.log(userD) // 4 lodash lib ... // ...