Skip to main content

no-dynamic-delete

禁止在计算键表达式上使用 delete 运算符.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict" 可启用此规则。

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

删除动态计算的键可能很危险,并且在某些情况下没有得到很好的优化。在非运行时常量的键上使用 delete 运算符可能表明你使用了错误的数据结构。如果你将对象用作键值集合,请考虑使用 MapSet

¥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.

动态添加和删除对象中的键可能会导致偶尔出现边缘情况错误。例如,某些对象使用 "隐藏属性"(例如 __data)进行私有存储,删除它们会破坏对象的内部状态。此外,delete 无法删除继承的属性或不可配置的属性。这使得它与任何比普通对象更复杂的东西交互不良:

¥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:

  • 数组的 length 是不可配置的,删除它是一个运行时错误。

    ¥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.

  • 有时,delete 只会删除自己的属性,而继承的属性保持不变。例如,删除函数的 name 属性只会删除自己的属性,但还会保留 Function.prototype.name 属性。

    ¥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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-dynamic-delete": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

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

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

当你知道你的密钥可以安全删除时,此规则可能就没有必要了。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥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.

资源