如何配置typescript-eslint naming-convention兼容纯数字对象属性?
问题
将@typescript-eslint/eslint-plugin和@typescript-eslint/parser从5.9.1版本升级至5.38.1版本后,执行eslint .时发现:非方括号包裹的纯数字对象属性会触发警告,而方括号形式的数字属性则可正常通过校验。
当前.eslintrc相关配置如下:
'@typescript-eslint/naming-convention': ['warn', { 'selector': 'property', 'format': ['strictCamelCase'] }],
期望在代码(如测试文件)中使用如下对象时,达到对应校验效果:
{ 0: true, // 应被允许;当前触发警告 8: false, // 应被允许;当前触发警告 [12]: true, // 可正常通过 "foo": "bar", // 可正常通过 "foo-bar": "baz" // 应触发警告,因不符合strictCamelCase }
纯数字属性触发的错误信息示例:
warning Object Literal Property name `3` must match one of the following formats: strictCamelCase @typescript-eslint/naming-convention
需要调整ESLint配置,既能保留命名规范校验,又允许纯数字属性(非方括号包裹的形式)。
解决方案
在@typescript-eslint/naming-convention规则中添加filter选项,通过正则匹配排除纯数字属性,同时保留对其他属性的strictCamelCase校验。修改后的配置如下:
'@typescript-eslint/naming-convention': ['warn', { 'selector': 'property', 'format': ['strictCamelCase'], 'filter': { 'regex': '^\\d+$', 'match': false } } ],
配置说明:
filter.regex: '^\\d+$':匹配由一个或多个数字组成的属性名filter.match: false:表示不应用当前规则的格式校验到匹配该正则的属性上
校验效果验证:
0: true、8: false:纯数字属性,匹配正则,跳过strictCamelCase校验,不再触发警告[12]: true:方括号包裹的数字属性,本身不会被该规则的propertyselector捕获,保持正常通过"foo": "bar":符合strictCamelCase,正常通过"foo-bar": "baz":不符合strictCamelCase,触发警告
这样既保留了对常规属性的命名规范校验,又允许使用纯数字形式的对象属性。
内容的提问来源于stack exchange,提问作者mm689
相关产品推荐
相关产品推荐

