跳至主要內容

ban-types

禁止某些類型。

擴充 "plugin:@typescript-eslint/recommended" ESLint 的設定 中啟用這條規則。

🔧

這條規則回報的一些問題能夠自動透過 ESLint 指令列選項的.

建議手動修正。

有些內建的類型有別名,而有些類型被視為危險或有害。為了維持一致性和安全性,通常禁止特定類型的做法是好的。

這條規則會禁止特定的類型,並建議使用替代方案。請注意,這不會禁止對應的執行時期物件的使用。
module.exports = {
"rules": {
"@typescript-eslint/ban-types": "error"
}
};

.eslintrc.cjs

在練習區中嘗試此規則 ↗

範例

// use lower-case primitives for consistency
const str: String = 'foo';
const bool: Boolean = true;
const num: Number = 1;
const symb: Symbol = Symbol('foo');
const bigInt: BigInt = 1n;

// use a proper function type
const func: Function = () => 1;

// use safer object types
const lowerObj: Object = {};
const capitalObj: Object = { a: 'string' };

const curly1: {} = 1;
const curly2: {} = { a: 'string' };
✅ 正確

在 Playground 中開啟

選項

type BanConfig =
/** Bans a type */
| {
/** Type to autofix replace with. Note that autofixers can be applied automatically - so you need to be careful with this option. */
fixWith?: string;
/** Custom error message */
message?: string;
/** Types to suggest replacing with. */
suggest?: string[];
}
/** Bans the type with a custom message */
| string
/** Bans the type with the default message */
| null
/** Bans the type with the default message */
| true
/** Un-bans the type (useful when paired with `extendDefaults`) */
| false;

type Options = [
{
extendDefaults?: boolean;
types?: {
[k: string]: BanConfig;
};
},
];

const defaultOptions: Options = [
{
/* See below for default options */
},
];

預設選項提供一組「最佳實務」,用來為您的程式庫提供安全性及標準化

  • 不要使用大寫基本型別,為了一致,您應該使用小寫型別。
  • 避免使用 Function 型別,由於以下原因,它的安全性低
    • 在呼叫該值時它不提供型別安全性,這表示很容易提供錯誤的引數。
    • 它接受類別宣告,由於它們在未帶有 new 關鍵字的呼叫下會失敗,因此它在被呼叫時會失敗。
  • 避免使用 Object{} 型別,因為它們表示「任何非空值」。
預設選項
const defaultTypes: Types = {
String: {
message: 'Use string instead',
fixWith: 'string',
},
Boolean: {
message: 'Use boolean instead',
fixWith: 'boolean',
},
Number: {
message: 'Use number instead',
fixWith: 'number',
},
Symbol: {
message: 'Use symbol instead',
fixWith: 'symbol',
},
BigInt: {
message: 'Use bigint instead',
fixWith: 'bigint',
},

Function: {
message: [
'The `Function` type accepts any function-like value.',
'It provides no type safety when calling the function, which can be a common source of bugs.',
'It also accepts things like class declarations, which will throw at runtime as they will not be called with `new`.',
'If you are expecting the function to accept certain arguments, you should explicitly define the function shape.',
].join('\n'),
},

// object typing
Object: {
message: [
'The `Object` type actually means "any non-nullish value", so it is marginally better than `unknown`.',
'- If you want a type meaning "any object", you probably want `object` instead.',
'- If you want a type meaning "any value", you probably want `unknown` instead.',
'- If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead.',
].join('\n'),
suggest: ['object', 'unknown', 'NonNullable<unknown>'],
},
'{}': {
message: [
'`{}` actually means "any non-nullish value".',
'- If you want a type meaning "any object", you probably want `object` instead.',
'- If you want a type meaning "any value", you probably want `unknown` instead.',
'- If you want a type meaning "empty object", you probably want `Record<string, never>` instead.',
'- If you really want a type meaning "any non-nullish value", you probably want `NonNullable<unknown>` instead.',
].join('\n'),
suggest: [
'object',
'unknown',
'Record<string, never>',
'NonNullable<unknown>',
],
},
};

types

一個物件,其金鑰是您要禁止的型別,而值是錯誤訊息。

該型別可以是型別名稱字面量 (Foo),一個具有泛型參數實際執行個體 (Foo<Bar>) 的型別名稱,一個空的物件字面量 ({}),或一個空的陣列型別 ([])。

這些值可以是

  • 一個字串,作為要報告的錯誤訊息;或
  • false,用來特別取消禁止此型別 (在您使用 extendDefaults 時很有用);或
  • 一個具有以下屬性的物件
    • message: string - 在與該型別相符時要顯示的訊息。
    • fixWith?: string - 在執行修正程式時用來取代已禁止型別的字串。若未提供,將不進行修正。
    • suggest?: string[] - 一個已禁止型別的建議替換清單。

extendDefaults

如果您正在指定自訂 types,您可以設定 true 來延伸預設的 types 設定。這是個省力的方便選項,讓您在新增其他型別時不必複製預設設定。

如果這是 false,該規則只會使用設定中定義的型別。

範例設定

{
"@typescript-eslint/ban-types": [
"error",
{
"types": {
// add a custom message to help explain why not to use it
"Foo": "Don't use Foo because it is unsafe",

// add a custom message, AND tell the plugin how to fix it
"OldAPI": {
"message": "Use NewAPI instead",
"fixWith": "NewAPI",
},

// un-ban a type that's banned by default
"{}": false,
},
"extendDefaults": true,
},
],
}

何時不用它

如果您的專案是個罕見的專案,會故意處理基本型的類別等效項,那麼啟動預設的 ban-types 選項可能不值得。您可能會考慮在那些特定情況下使用 ESLint disable 留言,而不是完全停用這項規則。

資源