no-redundant-type-constituents
禁止成員的聯盟與交集,這些成員沒有作用或會覆寫類型資訊。
💭
此規則需要 類型資訊 才能執行。
某些類型可以覆寫聯盟或交集中的其他類型(「組成部分」)和/或被其他類型覆寫。TypeScript 的類型集合論包括了構成部分類型在父聯盟或交集中可能沒有用的情況。
在 |
聯盟中
any
和unknown
會「覆寫」所有其他聯盟成員never
會從聯盟中刪除,但回傳類型位置除外- 像是
string
的基本類型會「覆寫」類型文字(例如""
)
在 &
交集中
any
和never
會「覆寫」所有其他交集成員unknown
會從交集中刪除- 文字類型會「覆寫」基本類型交集中的所有類型
- 文字類型(例如
""
)會「覆寫」任何原始類型(例如string
)
.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/no-redundant-type-constituents": "error"
}
};
在遊樂場測試這項規則 ↗
範例
- ❌ 不正確
- ✅ 正確
type UnionAny = any | 'foo';
type UnionUnknown = unknown | 'foo';
type UnionNever = never | 'foo';
type UnionBooleanLiteral = boolean | false;
type UnionNumberLiteral = number | 1;
type UnionStringLiteral = string | 'foo';
type IntersectionAny = any & 'foo';
type IntersectionUnknown = string & unknown;
type IntersectionNever = string | never;
type IntersectionBooleanLiteral = boolean & false;
type IntersectionNumberLiteral = number & 1;
type IntersectionStringLiteral = string & 'foo';
在遊樂場中開啟type UnionAny = any;
type UnionUnknown = unknown;
type UnionNever = never;
type UnionBooleanLiteral = boolean;
type UnionNumberLiteral = number;
type UnionStringLiteral = string;
type IntersectionAny = any;
type IntersectionUnknown = string;
type IntersectionNever = string;
type IntersectionBooleanLiteral = false;
type IntersectionNumberLiteral = 1;
type IntersectionStringLiteral = 'foo';
在遊樂場中開啟限制
這項規則會安全地運作,而且只用於底層型態、頂層型態,以及比較文字類型與原始類型。
選項
這項規則不可設定。
何時不使用
一些專案偶爾會選擇包含多餘的類型組成以供文件使用。例如,下列程式碼在聯集中包含 string
,即使 unknown
讓它變成多餘的類型
/**
* Normally a string name, but sometimes arbitrary unknown data.
*/
type NameOrOther = string | unknown;
如果你非常喜歡這些不必要的類型組成,這項規則可能不適合你。
深入探討
相較於傳統的程式碼檢查規則,類型檢查的程式碼檢查規則比較強大,但也需要設定 類型檢查的程式碼檢查。如果在啟用類型檢查規則後遇到效能衰退的問題,請參閱 效能疑難排解。