Search code examples
typescript

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:

{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)