no-restricted-types
禁止某些类型.
此规则报告的一些问题可通过 --fix
ESLint 命令行选项自动修复。
此规则报告的一些问题可以通过编辑器 建议 手动修复。
有时禁止在类型注释中使用特定类型会很有用。例如,一个项目可能正在从使用一种类型迁移到另一种类型,并希望禁止对旧类型的引用。
¥It can sometimes be useful to ban specific types from being used in type annotations. For example, a project might be migrating from using one type to another, and want to ban references to the old type.
此规则可以配置为禁止特定类型的列表并可以建议替代方案。请注意,它不会 禁止使用相应的运行时对象。
¥This rule can be configured to ban a list of specific types and can suggest alternatives. Note that it does not ban the corresponding runtime objects from being used.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/no-restricted-types": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/no-restricted-types": "error"
}
};
在线运行试试这个规则 ↗
选项
该规则接受以下选项:
type BanConfig =
/** 使用自定义消息禁止类型。 */
| string
/** 使用默认消息禁止类型。 */
| true
/** 禁止类型。 */
| {
/** Type to autofix replace with. Note that autofixers can be applied automatically - so you need to be careful with this option. */
fixWith?: string;
/** 自定义错误消息。 */
message?: string;
/** 建议替换的类型。 */
suggest?: string[];
};
type Options = [
{
/** An object whose keys are the types you want to ban, and the values are error messages. */
types?: {
[k: string]: BanConfig;
};
},
];
const defaultOptions: Options = [{}];
¥Options
types
An object whose keys are the types you want to ban, and the values are error messages.
类型可以是类型名称字面量(OldType
),也可以是具有泛型参数实例的类型名称(OldType<MyArgument>
)。
¥The type can either be a type name literal (OldType
) or a a type name with generic parameter instantiation(s) (OldType<MyArgument>
).
这些值可以是:
¥The values can be:
-
一个字符串,即要报告的错误信息;or
¥A string, which is the error message to be reported; or
-
具有以下属性的对象:
¥An object with the following properties:
-
message: string
:类型匹配时显示的消息。¥
message: string
: the message to display when the type is matched. -
fixWith?: string
:运行修复程序时用来替换被禁止类型的字符串。如果省略此项,则不会进行任何修复。¥
fixWith?: string
: a string to replace the banned type with when the fixer is run. If this is omitted, no fix will be done. -
suggest?: string[]
:禁止类型的建议替换列表。¥
suggest?: string[]
: a list of suggested replacements for the banned type.
-
配置示例:
¥Example configuration:
{
"@typescript-eslint/no-restricted-types": [
"error",
{
"types": {
// add a custom message to help explain why not to use it
"OldType": "Don't use OldType because it is unsafe",
// add a custom message, and tell the plugin how to fix it
"OldAPI": {
"message": "Use NewAPI instead",
"fixWith": "NewAPI",
},
// add a custom message, and tell the plugin how to suggest a fix
"SoonToBeOldAPI": {
"message": "Use NewAPI instead",
"suggest": ["NewAPIOne", "NewAPITwo"],
},
},
},
],
}
何时不使用它
¥When Not To Use It
如果你不需要禁止在类型注释中使用特定类型,则不需要此规则。
¥If you have no need to ban specific types from being used in type annotations, you don't need this rule.
相关
¥Related To