0

我需要对接口或类型中的属性使用snake_case。我camelcase

'camelcase': ["error", {properties: "never"}],

正如它在文档中提到的那样。它不适用于接口和类型,但适用于 JS 对象。

export const test = {
    a_b: 1, // OK. No error
};

export interface ITest {
    a_b: number, // Identifier 'a_b' is not in camel case.eslint(camelcase)
}

export type TTest = {
    a_b: number, // Identifier 'a_b' is not in camel case.eslint(camelcase)
}

当我将规则设置为 时,错误消失'off',因此此规则适用于 .ts 文件。

那么如何在 TS 中使用 snake_case 呢?谢谢。

4

1 回答 1

4

我相信该规则不适用于类型,我建议通过在您的 ESLint 中实现以下块来为 TypeScript 文件禁用此规则。

{
    "rules": {
        "camelcase": ["error"],
    },
    "overrides": [
        {
          "files": ["**/*.ts", "**/*.tsx"],
          "rules": {
            "camelcase": ["off"]
          }
        }
    ],
}

一旦我们禁用了该规则,我们就可以引入@typescript-eslint/eslint-plugin一个额外的 linting 规则,它将正确地 lint 接口和类型中的属性。

注意:如果你还没有安装插件和解析器,你必须安装,说明可以在这里找到:https ://www.npmjs.com/package/@typescript-eslint/eslint-plugin

参考@typescript-eslint/naming-conventionhttps ://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md

{
    "plugins": ["@typescript-eslint"],
    "parser": "@typescript-eslint/parser",
    "rules": {
        "camelcase": ["error"],
        "@typescript-eslint/naming-convention": [
            "error",
            { "selector": "property", "format": ["snake_case"] }
        ]
    },
    "overrides": [
        {
          "files": ["**/*.ts", "**/*.tsx"],
          "rules": {
            "camelcase": ["off"]
          }
        }
    ],
}
于 2020-07-06T09:29:44.290 回答