I have tried to read how to delete a property from an object in here: How do I remove a property from a JavaScript object?
it should use delete, I try it like this
const eventData = {...myEvent}; // myEvent is an instance of my `Event` class
delete eventData.coordinate; // I have error in here
but I have error like this

The operand of a 'delete' operator must be optional.ts(2790)
and then I read this : Typescript does not infer about delete operator and spread operator?
it seems to remove that error is by changing my tsconfig.json file using
{
"compilerOptions": {
...
"strictNullChecks": false,
}
...
}
but if I implement this, I will no longer have null checking
so how to delete a property from an object in Typescript without the operand of a 'delete' operator must be optional error?
Typescript warns you about breaking the contract (the object won't have the required property anymore). One of the possible ways would be omitting the property when you cloning the object:
const myEvent = {
coordinate: 1,
foo: 'foo',
bar: true
};
const { coordinate, ...eventData } = myEvent;
// eventData is of type { foo: string; bar: boolean; }
Playground
Operands for
deletemust be optional. When using thedeleteoperator instrictNullChecks, the operand must beany,unknown,never, or be optional (in that it containsundefinedin the type). Otherwise, use of thedeleteoperator is an error.
Docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With