Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the logic behind the TypeScript error "The operand of a 'delete' operator must be optional"?

This is the new error that is coming in typescript code.

I am not able to realize the logic behind it
Documentation

/*When using the delete operator in strictNullChecks,  the operand must now be any, unknown, never, or be optional  (in that it contains undefined in the type). Otherwise, use of the delete operator is an error.*/  interface Thing {   prop: string; }  function f(x: Thing) {   delete x.prop; // throws error = The operand of a 'delete' operator must be optional. } 
like image 277
Akshay Vijay Jain Avatar asked Sep 02 '20 08:09

Akshay Vijay Jain


People also ask

Is the operand of a delete operator must be optional?

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.

How do I make my properties optional in typescript?

To make a single property in a type optional, create a utility type that takes a type and the property name as parameters and constructs a new type with the specific property marked as optional.

Does delete return value?

1 Answer. Explanation: The delete operator doesn't return any value. Its function is to delete the memory allocated for an object. This is done in reverse way as that new operator works.


1 Answers

I am not able to realize the logic behind it

The logic as I understand is the following:

Interface Thing is a contract asking to have a (non-null, non-undefined) prop as a string.

If one removes the property, then the contract is not implemented anymore.

If you want it still valid when removed, just declare it as optional with a ?: prop?: string

I'm actually surprised that this was not causing error in earlier versions of TypeScript.

like image 139
Pac0 Avatar answered Sep 19 '22 11:09

Pac0