no-redeclare
不允许变量重新声明.
This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.
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.
This rule extends the base no-redeclare
rule from ESLint core. 它添加了对 TypeScript 函数重载和声明合并的支持。
¥It adds support for TypeScript function overloads, and declaration merging.
如何使用
- 扁平配置
- 旧版配置
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"no-redeclare": "off",
"@typescript-eslint/no-redeclare": "error"
}
});
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-redeclare": "off",
"@typescript-eslint/no-redeclare": "error"
}
};
在线运行试试这个规则 ↗
选项
See eslint/no-redeclare
's options.
¥Options
该规则添加了以下选项:
¥This rule adds the following options:
interface Options extends BaseNoRedeclareOptions {
ignoreDeclarationMerge?: boolean;
}
const defaultOptions: Options = {
...baseNoRedeclareDefaultOptions,
ignoreDeclarationMerge: true,
};
ignoreDeclarationMerge
是否忽略某些 TypeScript 声明类型之间的声明合并。 Default: true
.
启用此选项后,将忽略以下设置:
¥The following sets will be ignored when this option is enabled:
-
接口+接口
¥interface + interface
-
命名空间+命名空间
¥namespace + namespace
-
类+接口
¥class + interface
-
类+命名空间
¥class + namespace
-
类+接口+命名空间
¥class + interface + namespace
-
函数+命名空间
¥function + namespace
-
枚举+命名空间
¥enum + namespace
带有 { 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 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