Skip to main content

no-dynamic-delete

Disallow using the delete operator on computed key expressions.

πŸ”’

Extending "plugin:@typescript-eslint/strict" in an ESLint configuration enables this rule.

πŸ”§

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

Deleting dynamically computed keys can be dangerous and in some cases not well optimized. Using the delete operator on keys that aren't runtime constants could be a sign that you're using the wrong data structures. Consider using a Map or Set if you’re using an object as a key-value collection.

Dynamically adding and removing keys from objects can cause occasional edge case bugs. For example, some objects use "hidden properties" (such as __data) for private storage, and deleting them can break the object's internal state. Furthermore, delete cannot remove inherited properties or non-configurable properties. This makes it interact badly with anything more complicated than a plain object:

  • The length of an array is non-configurable, and deleting it is a runtime error.
  • You can't remove properties on the prototype of an object, such as deleting methods from class instances.
  • Sometimes, delete only removes the own property, leaving the inherited property intact. For example, deleting the name property of a function only removes the own property, but there's also a Function.prototype.name property that remains.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-dynamic-delete": "error"
}
};

Try this rule in the playground β†—

Examples​

// Dynamic, difficult-to-reason-about lookups
const name = 'name';
delete container[name];
delete container[name.toUpperCase()];
Open in Playground

Options​

This rule is not configurable.

When Not To Use It​

When you know your keys are safe to delete, this rule can be unnecessary. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

Do not consider this rule as performance advice before profiling your code's bottlenecks. Even repeated minor performance slowdowns likely do not significantly affect your application's general perceived speed.

Resources​