no-unsafe-declaration-merging
不允許不安全的宣告合併。
✅
擴充 "plugin:@typescript-eslint/recommended"
in an ESLint configuration enables this rule.
TypeScript 的「宣告合併」支援合併名稱相同的個別宣告。
類別和介面的宣告合併並不安全。TypeScript 編譯器不會檢查屬性的初始化,可能會導致 TypeScript 未偵測出會導致執行時期錯誤的程式碼。
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"
}
};
在線上遊場模式中嘗試這項規則 ↗
範例
- ❌ 錯誤
- ✅ 正確
選項
此規則無法設定。
不使用時
如果你的專案特地定義類別與介面為不安全的宣告合併模式,則這條規則可能不適合你。你可能會考慮使用 ESLint 禁用註解 針對特定情況,而不是完全禁用這條規則。