Eslint Typescript“无隐式任何”规则

问题描述 投票:0回答:2

我正在使用 eslint 设置一个新的 typescript 项目。我正在尝试正确设置 eslint 规则,以便

tsc
命令运行时不会出现错误。我在
tsconfig.json
中使用的“noImplicitAny”规则有问题,但我无法在 eslint 中检查这一点。

.eslintrc.js:

module.exports = {
    extends: [
        "eslint:recommended",
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
    ],
    parser: "@typescript-eslint/parser",
    parserOptions: {
        project: ["tsconfig.json"],
        sourceType: "module",
    },
    rules: {
        "no-undef": "warn",
    },
    plugins: ["@typescript-eslint"],
    settings: {
        "import/resolver": {
            node: {
                extensions: [".js", ".ts"],
            },
        },
    },
};

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "ES6",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

简而言之,我希望 eslint 检查隐式的 any 并警告其使用情况。如何配置

.eslintrc.js
中的规则来实现此目的?

typescript eslint
2个回答
20
投票

TypeScript-ESLint 中已实现了许多

no-unsafe-*
规则:

这些都是独立的规则,但它们也都已集成到 Typescript-ESLint 官方 推荐类型检查配置。

export default tseslint.config(
  eslint.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,
  ...tseslint.configs.stylisticTypeChecked,
);

检查此处了解配置定义的其他可能性。

类似地,还有

no-explicit-any
。将所有这些放在一起,您应该得到充分的保护,免受
any
问题的困扰。


2
投票

更新:

以前使用 typedef 的用法很烦人,因为即使 typescript 可以隐式知道它是什么,它仍然用警告标记它。

我现在使用以下规则:

'@typescript-eslint/no-unsafe-call': 'warn',

当变量确实是我所看到的任何变量时,这会发出警告。

以前:

eslint 拒绝添加 no-implicit-any,因为它重复了打字稿规则。

但是,他们确实制定了一条不应永久使用的转换规则,这符合您的要求。一旦您可以在 tsconfig 文件中打开这些选项,您就应该删除此规则。

这允许对普通函数和箭头函数中的隐式参数或参数发出警告。还有比注释掉的选项更多的选项,下面链接了文档。

我对这条规则的一个问题是,如果打字稿可以隐式地弄清楚它应该是什么,那么这条规则仍然将其标记为一个问题。由于它应该只是暂时的,直到您可以打开打字稿规则,所以我只是忽略这些问题。

    '@typescript-eslint/typedef': [
      'warn',
      {
        parameter: true,
        arrowParameter: true,
        // variableDeclaration: true,
        // memberVariableDeclaration: true,
        // objectDestructuring: true,
      },
    ],

链接到 github 问题不允许 no-implicit-any https://github.com/typescript-eslint/typescript-eslint/issues/3979

typedef 信息的文档 https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/typedef.md

© www.soinside.com 2019 - 2024. All rights reserved.