no-dynamic-delete
Disallow using the
delete
operator on computed key expressions.
在 ESLint 配置 中扩展"plugin:@typescript-eslint/strict"
可启用此规则。
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
删除动态计算的键可能很危险,并且在某些情况下没有得到很好的优化。
在不是运行时常量的键上使用 delete
运算符可能表明你使用了错误的数据结构。
将 Object
与添加和删除的键一起使用可能会导致偶尔出现边缘情况错误,例如键名为 "hasOwnProperty"
。
英: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.
Using Object
s with added and removed keys can cause occasional edge case bugs, such as if a key is named "hasOwnProperty"
.
如果你要存储对象集合,请考虑使用
Map
或Set
。
module.exports = {
"rules": {
"@typescript-eslint/no-dynamic-delete": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
// Can be replaced with the constant equivalents, such as container.aaa
delete container['aaa'];
delete container['Infinity'];
// Dynamic, difficult-to-reason-about lookups
const name = 'name';
delete container[name];
delete container[name.toUpperCase()];
Open in Playgroundconst container: { [i: string]: number } = {
/* ... */
};
// Constant runtime lookups by string index
delete container.aaa;
// Constants that must be accessed by []
delete container[7];
delete container['-Infinity'];
Open in Playground何时不使用它
当你知道你的密钥可以安全删除时,此规则可能就没有必要了。 你可以考虑在这些特定情况下使用 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.
选项
该规则不可配置。