Borislav Hadzhiev
Sun Feb 20 2022·2 min read
Photo by Vlad Gedroics
The error "the operand of a 'delete' operator must be optional" occurs when we
try to use the delete
operator to delete a property that is marked as
required. To solve the error use a question mark to mark the property as
optional before using the delete
operator.
Here is an example of how the error occurs.
// 👇️ const obj1: {name: string;} const obj1 = { name: 'Tom' }; // ⛔️ The operand of a 'delete' operator must be optional.ts(2790) delete obj1['name'];
The obj1
variable is an object that has the name
property pointing to a
string
value. The property is marked as required on the object, so trying to
delete it causes the error.
To get around this, you have to use a question mark to set the property to be optional.
// 👇️ const obj2: {name?: string | undefined;} const obj2: { name?: string } = { name: 'Tom' }; // ✅ works delete obj2['name']; console.log(obj2); // 👉️ {}
The name
property in the object is optional, so it can either be undefined
or a string
, which allows us to use the
delete
operator to remove the property from the object.
Here is an example of how you would do this with an interface.
interface Person { name?: string; } const obj: Person = { name: 'Tom' }; delete obj['name']; console.log(obj); // 👉️ {}
If you don't have access to the interface, you can use the Partial utility type to construct a new type with all properties set to optional.
interface Person { name: string; } // 👇️ const obj: Partial<Person> const obj: Partial<Person> = { name: 'Tom' }; delete obj['name']; console.log(obj); // 👉️ {}
The name
property is set to required in the Person
interface, so we had to
use the Partial
utility type to construct a new type with the properties set
to optional before using the delete
operator.
If you want to make only some of the properties on the interface optional, you can use the Omit and Pick utility types.
Here is an example where we make the name
and country
properties optional,
but leave the age
property as required.
interface Person { name: string; age: number; country: string; } const obj: Partial<Pick<Person, 'name' | 'country'>> & Omit<Person, 'name' | 'country'> = { name: 'Tom', age: 30, country: 'Chile', }; delete obj['name']; delete obj['country']; console.log(obj); // 👉️ {age: 30}
We used the Pick
utility type to pick out the name
and country
properties
from the Person
interface and make them optional.
Then we used the Omit
utility type to exclude the name
and country
properties from the Person
interface and combined the types.
All of the examples above work in the same way when using types instead of interfaces.
type Person = { name?: string; }; const obj: Person = { name: 'Tom', }; delete obj['name']; console.log(obj); // 👉️ {}