简体   繁体   English

为 typescript 接口标识符关闭 eslint camelCase

[英]Turn off eslint camelCase for typescript interface identifiers

I'm trying to migrate an existing JS repo to TypeScript. The problem is that projects' API responses are objects with identifiers in snake_case and this conflicts with default eslint camelCase rule.我正在尝试将现有的 JS 存储库迁移到 TypeScript。问题是项目的 API 响应是带有snake_case标识符的对象,这与默认的 eslint camelCase规则冲突。

Before the migration we were handling snake_case object identifiers with this rule in .eslintrc.js :在迁移之前,我们在 .eslintrc.js 中使用此规则处理snake_case .eslintrc.js标识符:

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

And could have objects like this in our code:在我们的代码中可以有这样的对象:

const { variable_name } = await axios(url)

But after moving to TypeScript, these identifiers are also going show up in interfaces.但是在移动到 TypeScript 之后,这些标识符也会出现在界面中。

So basically I want to be able to have:所以基本上我希望能够拥有:

interface Model<T extends string> {
    type: T;
    id: number;
    variable_name: string;
    language_code: string;
}

But Typescript now throws:但是 Typescript 现在抛出:

Identifier 'variable_name' is not in camel case.

What rule should I have in my .eslintrc.js file to justify this?我的.eslintrc.js文件中应该有什么规则来证明这一点? Please note that my identifiers are not limited to those two listed above and there are dozens of others which I removed for simplicity.请注意,我的标识符不仅限于上面列出的那两个,还有许多其他标识符,为了简单起见,我删除了它们。

Keep in mind that JavaScript (for which ESLint is developed) doesn't know of types (eg. interfaces).请记住,JavaScript(为其开发 ESLint)不知道类型(例如接口)。

So I think this is what is happening while linting the file:所以我认为这是在检查文件时发生的事情:

  • The camelCase rule of ESLint applies to objects and their properties. ESLint 的camelCase规则适用于对象及其属性。
  • The parser of ESLint doesn't understand that you have an interface and thinks that those are variables within another block. ESLint 的解析器不理解你有一个接口,并认为那些是另一个块中的变量。 Therefore the check leads to a wrong result.因此检查会导致错误的结果。

I think what you need to do is:我认为你需要做的是:

  • Disable the camelCase rule (at least for your TypeScript files).禁用camelCase规则(至少对于您的 TypeScript 文件)。
  • Use the naming-convention rule instead and configure it as you need.请改用命名约定规则并根据需要进行配置。

This should work:这应该有效:

"@typescript-eslint/naming-convention": [
    "error",
    {
        "selector": "default",
        "format": ["camelCase"]
    },
    {
        "selector": "typeProperty",
        "format": null
    }
]

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

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