Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete a property from an object in Typescript without the operand of a 'delete' operator must be optional error?

Tags:

typescript

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

enter image description here

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?

like image 974
Agung Laksana Avatar asked Nov 26 '25 03:11

Agung Laksana


1 Answers

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 delete must be optional. When using the delete operator in strictNullChecks, the operand must be any, unknown, never, or be optional (in that it contains undefined in the type). Otherwise, use of the delete operator is an error.

Docs

like image 107
Aleksey L. Avatar answered Nov 28 '25 16:11

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!