Skip to main content

no-redeclare

Disallow variable redeclaration.


danger

The code problem checked by this ESLint rule is automatically checked by the TypeScript compiler. Thus, it is not recommended to turn on this rule in new TypeScript projects. You only need to enable this rule if you prefer the ESLint error messages over the TypeScript compiler error messages.

此规则扩展了基本 eslint/no-redeclare 规则。 它添加了对 TypeScript 函数重载和声明合并的支持。

英:This rule extends the base eslint/no-redeclare rule. It adds support for TypeScript function overloads, and declaration merging.

选项

该规则添加了以下选项:

英:This rule adds the following options:

interface Options extends BaseNoRedeclareOptions {
ignoreDeclarationMerge?: boolean;
}

const defaultOptions: Options = {
...baseNoRedeclareDefaultOptions,
ignoreDeclarationMerge: true,
};

ignoreDeclarationMerge

当设置为 true 时,规则将忽略以下集合之间的声明合并:

英:When set to true, the rule will ignore declaration merges between the following sets:

  • 接口+接口
  • 命名空间+命名空间
  • 类+接口
  • 类+命名空间
  • 类+接口+命名空间
  • 函数+命名空间
  • 枚举+命名空间

correct 代码与 { ignoreDeclarationMerge: true } 的示例:

英:Examples of correct code with { 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 {}
Open in Playground

注意: 即使此选项设置为 true,如果你将类型和变量命名为相同名称,此规则也会报告。 这是故意的。 将变量和类型以及变量声明为相同通常是一种意外,并且可能会导致代码难以理解。 如果你在极少数情况下故意将类型命名为与变量相同的名称,请使用禁用注释。 例如:

英:Note: Even with this option set to true, this rule will report if you name a type and a variable the same name. This is intentional. Declaring a variable and a type and a variable the same is usually an accident, and it can lead to hard-to-understand code. If you have a rare case where you're intentionally naming a type the same name as a variable, use a disable comment. For example:

type something = string;
// eslint-disable-next-line @typescript-eslint/no-redeclare -- intentionally naming the variable the same as the type
const something = 2;
Open in Playground

如何使用

.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"
}
};
在线运行试试这个规则 ↗

选项

参见 eslint/no-redeclare 选项

资源

摘自 ❤️ ESLint 内核