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

Can I write my own custom rule in eslint config?

是否可以在 eslint 配置中编写自定义规则? 我的案例基于 'any' 类型。在 eslint 文档中是规则“@typescript-eslint/no-explicit-any”,但它对我来说太强大了。我想像这样阻止分配:

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

是否可以屏蔽此案例?

您可以使用 no-unsafe-assignment rule 代替 no-explicit-any 规则。

This rule disallows assigning any to a variable, and assigning any[] to an array destructuring. 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. For example, it will error if you assign Set to a variable declared as Set.

.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
              },
            },
          ],
      }