Skip to main content

ban-types

Disallow certain types.

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

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。


某些内置类型具有别名,而某些类型被认为是危险或有害的。 禁止某些类型通常是一个好主意,以帮助保持一致性和安全性。

英:Some built-in types have aliases, while some types are considered dangerous or harmful. It's often a good idea to ban certain types to help with consistency and safety.

该规则禁止特定类型,并可以建议替代方案。 请注意,它不会禁止使用相应的运行时对象。

英:This rule bans specific types and can suggest alternatives. Note that it does not ban the corresponding runtime objects from being used.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/ban-types": "error"
}
};
在线运行试试这个规则 ↗

示例

具有默认选项的代码示例:

英:Examples of code with the default options:

// 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' };
Open in Playground

选项

默认选项提供了一组 "最佳实践",旨在为你的代码库提供安全性和标准化:

英:The default options provide a set of "best practices", intended to provide safety and standardization in your codebase:

  • 不要使用大写的原始类型,应该使用小写的类型以保持一致性。
  • 避免使用 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

一个对象,其键是要禁止的类型,值是错误消息。

英:An object whose keys are the types you want to ban, and the values are error messages.

该类型可以是类型名称字面量 (Foo)、具有泛型参数实例化的类型名称 (Foo<Bar>)、空对象字面量 ({}) 或空元组类型 ([])。

英:The type can either be a type name literal (Foo), a type name with generic parameter instantiation(s) (Foo<Bar>), the empty object literal ({}), or the empty tuple type ([]).

这些值可以是:

英:The values can be:

  • 一个字符串,即要报告的错误信息; or
  • false 专门取消禁止此类型(当你使用 extendDefaults 时很有用); or
  • 具有以下属性的对象:
    • message: string - 类型匹配时显示的消息。
    • fixWith?: string - 运行修复程序时替换禁止类型的字符串。 如果省略此项,则不会进行任何修复。
    • suggest?: string[] - 禁用类型的建议替代品列表。

extendDefaults

如果你指定自定义 types,则可以将其设置为 true 以扩展默认 types 配置。 这是一个方便的选项,可以让你在添加其他类型时避免跨默认值进行复制。

英:If you're specifying custom types, you can set this to true to extend the default types configuration. This is a convenience option to save you copying across the defaults when adding another type.

如果这是 false,则规则将仅使用你的配置中定义的类型。

英:If this is false, the rule will only use the types defined in your configuration.

配置示例:

英:Example configuration:

{
"@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 禁用注释,而不是完全禁用此规则。

英:If your project is a rare one that intentionally deals with the class equivalents of primitives, it might not be worthwhile to enable the default ban-types options. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

选项

该规则接受以下选项

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 */
},
];

资源