Ask Question

How can I copy an object in TypeScript?

I need an util function which returns a copy (decoupled) of the passed object and the return object has to have the same type.
Is there any generic solution for that?
Thx in advance! ✌️

TypeScript

1544 views

AuthorΒ΄s AnkiCodes image

AnkiCodes

πŸ‘
1
πŸ‘€
1
Last edited on

1 Answer available

Best answer

You may want to look into lodash's cloneDeep. See @types/lodash package for the types.

For shallow copying you can spread, without a need for an additional util function.

const a = { country: 'Catalonia' };
const b = { ...country }; // equivalent to Object.assign({}, a)
πŸ‘
2