Last updated: Feb 27, 2024
Reading timeยท2 min
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 obj: {name: string;} const obj = { name: 'Bobby Hadz' }; // โ๏ธ The operand of a 'delete' operator must be optional.ts(2790) delete obj['name'];
The obj
variable is an object that has the name
property with a string
value.
The property is marked as required on the object, so trying to delete it causes the error.
Use a question mark to set the property to optional to solve the error.
// ๐๏ธ const obj: {name?: string | undefined;} const obj: { name?: string } = { name: 'Bobby Hadz' }; // โ works delete obj['name']; console.log(obj); // ๐๏ธ {}
The name
property in the object is optional, so it can either be undefined
or a string
.
This 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: 'Bobby Hadz' }; delete obj['name']; console.log(obj); // ๐๏ธ {}
If you don't have access to the interface, 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: 'Bobby Hadz' }; 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: 'Bobby Hadz', 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: 'Bobby Hadz', }; delete obj['name']; console.log(obj); // ๐๏ธ {}