禁止重複類型成分
禁止合併或交集類型的重複組成。
✅
延伸 "plugin:@typescript-eslint/recommended-type-checked"
in an ESLint configuration enables this rule.
🔧
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
💭
This rule requires type information to run.
TypeScript 支持合併和交集類型中的類型(「組成」)相互為重複。但是,開發人員通常希望每個組成在它的交集或合併中是唯一的。重複的值會使程式碼過於冗長,並且通常會降低可讀性。
此規則不允許重複的聯集或交集成分。如果類型在類型系統中計算出的結果相同,則我們將類型視為重複。例如,給定 type A = string
和 type T = string | A
,此規則會標示 A
與 string
是同一個類型。
- ❌ 錯誤
- ✅ 正確
type T1 = 'A' | 'A';
type T2 = A | A | B;
type T3 = { a: string } & { a: string };
type T4 = [1, 2, 3] | [1, 2, 3];
type StringA = string;
type StringB = string;
type T5 = StringA | StringB;
在遊樂場中開啟type T1 = 'A' | 'B';
type T2 = A | B | C;
type T3 = { a: string } & { b: string };
type T4 = [1, 2, 3] | [1, 2, 3, 4];
type StringA = string;
type NumberB = number;
type T5 = StringA | NumberB;
在遊樂場中開啟.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-duplicate-type-constituents": "error"
}
};
在遊樂空中試用此規則↗
選項
此規則接受下列選項
type Options = [
{
ignoreIntersections?: boolean;
ignoreUnions?: boolean;
},
];
const defaultOptions: Options = [
{ ignoreIntersections: false, ignoreUnions: false },
];
ignoreIntersections
設定為 true 時,會略過交集類型成分的重複檢查。
ignoreUnions
設定為 true 時,會略過聯集類型成分的重複檢查。
何時不使用它
將別名的相同類型納入考量,有時有助於文件編寫。你可以考慮在這些特定情況下使用 ESLint 禁用註解,而非完全停用此規則。
在某些情況下,具品牌類型的可能是類型安全,可代表基礎資料類型的方式。
類型檢查後的 lint 規則比傳統的 lint 規則更強大,但必須設定 類型檢查後的 lint。如果您在啟用類型檢查後的規則後遇到效能降低,請參閱 效能疑難排解。