禁止重新声明
禁止变量重新声明。
危险
此 ESLint 规则检查的代码问题由 TypeScript 编译器自动检查。因此,不建议在新 TypeScript 项目中启用此规则。只有在您更喜欢 ESLint 错误消息而不是 TypeScript 编译器错误消息时,才需要启用此规则。
此规则扩展了基本 eslint/no-redeclare 规则。它为 TypeScript 函数重载和声明合并添加了支持。
如何使用
.eslintrc.cjs
module.exports = {
  "rules": {
    // Note: you must disable the base rule as it can report incorrect errors
    "no-redeclare": "off",
    "@typescript-eslint/no-redeclare": "error"
  }
};
在游乐场中尝试此规则 ↗
选项
此规则添加了以下选项
interface Options extends BaseNoRedeclareOptions {
  ignoreDeclarationMerge?: boolean;
}
const defaultOptions: Options = {
  ...baseNoRedeclareDefaultOptions,
  ignoreDeclarationMerge: true,
};
ignoreDeclarationMerge
当设置为 true 时,该规则将忽略以下集合之间的声明合并
- 接口 + 接口
- 命名空间 + 命名空间
- 类 + 接口
- 类 + 命名空间
- 类 + 接口 + 命名空间
- 函数 + 命名空间
- 枚举 + 命名空间
使用 { ignoreDeclarationMerge: true } 的正确代码示例
interface A {
  prop1: 1;
}
interface A {
  prop2: 2;
}
namespace Foo {
  export const a = 1;
}
namespace Foo {
  export const b = 2;
}
class Bar {}
namespace Bar {}
function Baz() {}
namespace Baz {}
注意:即使将此选项设置为 true,如果类型名称和变量名称相同,此规则也会报告。这是故意的。声明一个变量和一个类型以及一个变量相同通常是意外的,并且会导致难以理解的代码。如果您有罕见的情况需要有意地将类型命名为与变量相同的名称,请使用禁用注释。例如
type something = string;
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentionally naming the variable the same as the type
const something = 2;