Search code examples
javascripttypescripteslintrulesany

Can I write my own custom rule in eslint config?


Is it possible to write custom rule in eslint config? My case is based on type 'any'. In eslint doc is rule "@typescript-eslint/no-explicit-any", but it's too strong for me. I want to block assignment like this:

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

Is it possible to block this case?


Solution

  • You can use the no-unsafe-assignment rule instead of the no-explicit-any rule.

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