简体   繁体   English

我可以在 eslint 配置中编写自己的自定义规则吗?

[英]Can I write my own custom rule in eslint config?

Is it possible to write custom rule in eslint config?是否可以在 eslint 配置中编写自定义规则? My case is based on type 'any'.我的案例基于“任何”类型。 In eslint doc is rule "@typescript-eslint/no-explicit-any", but it's too strong for me.在 eslint doc 中是规则“@typescript-eslint/no-explicit-any”,但它对我来说太强大了。 I want to block assignment like this:我想阻止这样的分配:

const dontknow: any = ''; const name: string = dontknow;

Is it possible to block this case?是否有可能阻止这种情况?

You can use the no-unsafe-assignment rule instead of the no-explicit-any rule.您可以使用no-unsafe-assignment规则而不是no-explicit-any规则。 This rule disallows assigning any to a variable, and assigning any[] to an array destructuring.此规则不允许将 any 分配给变量,并将 any[] 分配给数组解构。 This rule also compares the assigned type to the variable's type to ensure you don't assign an unsafe any in a generic position to a receiver that's expecting a specific type.此规则还将分配的类型与变量的类型进行比较,以确保您不会将通用 position 中的不安全 any 分配给期望特定类型的接收器。 For example, it will error if you assign Set to a variable declared as Set.例如,如果将 Set 分配给声明为 Set 的变量,则会出错。

.eslintrc .eslintrc

  {
        "root": true,
        "parser": "@typescript-eslint/parser",
        "plugins": [
          "@typescript-eslint"
        ],
        "extends": [
          "eslint:recommended",
          "plugin:@typescript-eslint/eslint-recommended",
          "plugin:@typescript-eslint/recommended"
        ],
        "rules": { 
            "@typescript-eslint/no-unsafe-assignment": 2
        },
        "overrides": [
            {
              "files": ["*.ts", "*.tsx"], // Your TypeScript files extension
              "parserOptions": {
                "project": ["./tsconfig.json"], // Specify it only for TypeScript files
              },
            },
          ],
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM