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

Creating a new object in typescript based off an existing object

In TypeScript I have a base object as a template and I want to replicate that object changing just the one property similar to below:

interface user {
    name: string, 
    jobTitle: string
}

const employee: user = {name: 'Liane', jobTitle: 'Web Dev'}

const newEmployee1 = employee;
newEmployee1.name = 'James';
const newEmployee2 = employee;
newEmployee2.name = 'John';

However when I view the results in the console every employees name is ‘John’ as shown below:

{name: 'John', jobTitle: 'Web Dev'}
{name: 'John', jobTitle: 'Web Dev'}
{name: 'John', jobTitle: 'Web Dev'} 

I do understand this is due to object referencing, however I don’t want to reference the base employee I want to clone it as it own object independant from the other users. So when I console log the objects I’ll get:

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

{name: 'Liane', jobTitle: 'Web Dev'}
{name: 'James', jobTitle: 'Web Dev'}
{name: 'John', jobTitle: 'Web Dev'}

Is there any way for me to do this?

>Solution :

If you want to clone an existing object, I’d recommend the "spread operator"

// interface user {
//     name: string, 
//     jobTitle: string
// }

// const employee: user = {name: 'Liane', jobTitle: 'Web Dev'}
const employee = {name: 'Liane', jobTitle: 'Web Dev'}

const newEmployee1 = {
  ...employee,
  name: 'James'
};

const newEmployee2 = {
  ...employee,
  name: 'John'
};

console.log(employee)
console.log(newEmployee1)
console.log(newEmployee2)
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