Skip to main content

no-unsafe-declaration-merging

Disallow unsafe declaration merging.

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


TypeScript 的 "声明合并" 支持合并具有相同名称的单独声明。

英:TypeScript's "declaration merging" supports merging separate declarations with the same name.

类和接口之间的声明合并是不安全的。 TypeScript 编译器不会检查属性是否已初始化,这可能会导致 TypeScript 无法检测到会导致运行时错误的代码。

英:Declaration merging between classes and interfaces is unsafe. The TypeScript compiler doesn't check whether properties are initialized, which can cause lead to TypeScript not detecting code that will cause runtime errors.

interface Foo {
nums: number[];
}

class Foo {}

const foo = new Foo();

foo.nums.push(1); // Runtime Error: Cannot read properties of undefined.
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-unsafe-declaration-merging": "error"
}
};
在线运行试试这个规则 ↗

示例

interface Foo {}

class Foo {}
Open in Playground

何时不使用它

如果你的项目故意定义具有不安全声明合并模式的类和接口,则此规则可能不适合你。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

英:If your project intentionally defines classes and interfaces with unsafe declaration merging patterns, this rule might not be for you. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

进一步阅读

选项

该规则不可配置。

资源