ESLint禁用no-dupe-keys规则无效,寻求解决方案
解决TypeScript+ESLint中
no-dupe-keys禁用规则无效的问题 问题描述
在TypeScript+ESLint项目中遇到错误提示:An object literal cannot have multiple properties with the same name.,尝试用// eslint-disable-next-line no-dupe-keys在重复属性行上方禁用检查,但规则无效,代码仍被标记。在线ESLint Playground中该方法有效,但本地项目(配置及代码如下)无法生效。
代码示例
testFetch.ts
import fetch from 'node-fetch'; export function testRequest() { const url:string = 'https://example.com/api'; // eslint-disable-next-line camelcase const test_camel = 'sd' const body = { "key[0]": "arr_val_1", // eslint-disable-next-line no-dupe-keys "key[0]": "arr_val_2", // eslint-disable-next-line camelcase "key[1]": test_camel, } fetch(url, {body}) .then((res) => res.json()) .then((res) => console.log(res)) .catch((err) => console.error('error:' + err)); }
.eslintrc.cjs
/* eslint-env node */ module.exports = { extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'], parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], root: true, rules: { "no-dupe-keys": "error", camelcase: "error", }, ignorePatterns: [ "test/*", "dist/*", ".eslintrc.cjs" ], // "noInlineConfig": true, };
问题原因
你启用的是原生ESLint的no-dupe-keys规则,但在TypeScript场景下,实际触发错误的是@typescript-eslint/no-dupe-keys规则。原生规则会被TypeScript解析器覆盖,导致你针对原生规则的禁用注释不起作用。
解决方案
步骤1:替换规则名称
把禁用注释和ESLint配置中的规则名,都替换为TypeScript专属的@typescript-eslint/no-dupe-keys:
- 修改代码中的注释:
const body = { "key[0]": "arr_val_1", // eslint-disable-next-line @typescript-eslint/no-dupe-keys "key[0]": "arr_val_2", // eslint-disable-next-line camelcase "key[1]": test_camel, } - 更新
.eslintrc.cjs的规则配置:rules: { "@typescript-eslint/no-dupe-keys": "error", camelcase: "error", },
步骤2:验证生效
重启编辑器的ESLint插件或本地ESLint服务,再检查代码,重复属性的错误标记应该会消失。
补充说明
- 在线ESLint Playground可能未完全启用
@typescript-eslint插件规则,原生规则仍在生效,所以原生禁用注释能起作用;但本地TypeScript项目中,TypeScript解析器会优先使用专属规则,原生规则被忽略。 - 若需兼容两种规则,也可以同时禁用:
// eslint-disable-next-line no-dupe-keys, @typescript-eslint/no-dupe-keys,但更推荐直接使用TypeScript专属规则避免冲突。
内容的提问来源于stack exchange,提问作者mr.incredible
相关产品推荐
相关产品推荐

