Home > Enterprise >  How to delete a property from an object copy?
How to delete a property from an object copy?

Time:01-12

If for example I have an object that looks like this:

const rabbit = {
  color: 'blue',
  personalData: {
    name: 'Bob',
    age: 35
  }
}

and I make a copy of it using the spread operator and then try to delete a field:

const rabbitCopy = {
  ...rabbit
}
delete rabbitCopy.personalData.name

How can I avoid the message: "The operand of a 'delete' operator must be optional." I understand why this message appears as for typescript it doesn't make sense to let the user delete a property as it would break the contract... but in my case, I need to do it

How can I at the moment of copying the object, define the copy with optional components?

The only way I've seen to handle this scenario is the following but I don't quite understand what is happening:

delete (rabbitCopy.personalData as unknown as Record<string, unknown>).name

CodePudding user response:

enter image description here

You can tell Typescript that name is an optional property like this:

type Rabbit = {
  color: string;
  personalData: {
    name?: string;
    age: number;
  }
}

const rabbit: Rabbit = {
  color: 'blue',
  personalData: {
    name: 'Bob',
    age: 35
  }
}

And then this will not cause any errors:

const rabbitCopy = {
  ...rabbit
}
delete rabbitCopy.personalData.name

Try it here

CodePudding user response:

Create name field optional inside type and copy,

NOTE: When you delete it'll delete from rabbit object also, destructuring only creates a shallow copy.

type Rabbit = {
  color: string
  personalData: {
    name?: string;
    age: number;
  }
}

const rabbit:Rabbit = {
  color: 'blue',
  personalData: {
    name: 'Bob',
    age: 35
  }
}

const { name, ...personalData} = rabbit.personalData;
const copy = {
    ...rabbit,
    personalData
}
  •  Tags:  
  • Related