no-use-before-define
Disallow the use of variables before they are defined.
This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.
This rule extends the base no-use-before-define
rule from ESLint core. 它增加了对 type
、interface
和 enum
声明的支持。
¥It adds support for type
, interface
and enum
declarations.
如何使用
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "error"
}
});
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"no-use-before-define": "off",
"@typescript-eslint/no-use-before-define": "error"
}
};
在线运行试试这个规则 ↗
选项
See eslint/no-use-before-define
's options.
¥Options
该规则添加了以下选项:
¥This rule adds the following options:
interface Options extends BaseNoUseBeforeDefineOptions {
enums?: boolean;
typedefs?: boolean;
ignoreTypeReferences?: boolean;
}
const defaultOptions: Options = {
...baseNoUseBeforeDefineDefaultOptions,
enums: true,
typedefs: true,
ignoreTypeReferences: true,
};
enums
Whether to check references to enums. Default: true
.
如果这是 true
,则此规则会在枚举声明之前对枚举的每个引用发出警告。如果这是 false
,则当引用在子范围内时,此规则将忽略对枚举的引用。
¥If this is true
, this rule warns every reference to a enum before the enum declaration.
If this is false
, this rule will ignore references to enums, when the reference is in a child scope.
{ "enums": true }
选项的代码示例:
¥Examples of code for the { "enums": true }
option:
- ❌ Incorrect
- ✅ Correct
const x = Foo.FOO;
enum Foo {
FOO,
}
Open in Playgroundfunction foo() {
return Foo.FOO;
}
enum Foo {
FOO,
}
Open in Playgroundtypedefs
Whether to check references to types. Default: true
.
如果这是 true
,则此规则会在类型声明之前对类型的每个引用发出警告。如果这是 false
,则此规则将忽略对类型的引用。
¥If this is true
, this rule warns every reference to a type before the type declaration.
If this is false
, this rule will ignore references to types.
{ "typedefs": false }
选项的正确代码示例:
¥Examples of correct code for the { "typedefs": false }
option:
let myVar: StringOrNumber;
type StringOrNumber = string | number;
Open in PlaygroundignoreTypeReferences
Whether to ignore type references, such as in type annotations and assertions. Default: true
.
如果这是 true
,则此规则将忽略所有类型引用。如果这是 false
,这将检查所有类型引用。
¥If this is true
, this rule ignores all type references.
If this is false
, this will check all type references.
{ "ignoreTypeReferences": true }
选项的正确代码示例:
¥Examples of correct code for the { "ignoreTypeReferences": true }
option:
let var1: StringOrNumber;
type StringOrNumber = string | number;
let var2: Enum;
enum Enum {}
Open in Playground'## 资源'
Taken with ❤️ from ESLint core.