简体   繁体   中英

ESLint and snake_case inside TypeScript Type property

I need to use snake_case for properties inside my Interfaces or Types. I set rule camelcase with

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

as it mentioned in docs . And it doesn't work for interfaces and types but works for JS objects.

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)
}

Error is dissapears when I set the rule to 'off' , so this rule applies to.ts files.

So how can I use snake_case inside TS? Thanks.

I believe the rule does not work with types, I would recommend disabling this rule for TypeScript files by implementing the following blocks in your ESLint.

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

Once we've disabled that rule we can bring in @typescript-eslint/eslint-plugin to apply an additional linting rule where it will lint the properties in interfaces and types correctly.

Note: You'll have to install the plugin and parser if you haven't done so, instructions can be found here: https://www.npmjs.com/package/@typescript-eslint/eslint-plugin

Ref @typescript-eslint/naming-convention : https://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"]
          }
        }
    ],
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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