consistent-return
Require
return
statements to either always or never specify values.
该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。
This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.
This rule extends the base consistent-return
rule from ESLint core. 它增加了对返回 void
或 Promise<void>
的函数的支持。
¥It adds support for functions that return void
or Promise<void>
.
如果可能,建议使用 tsconfig 的 noImplicitReturns
选项而不是此规则。noImplicitReturns
由 TS 的类型信息和控制流分析提供支持,因此它比此规则具有更好的覆盖范围。
¥If possible, it is recommended to use tsconfig's noImplicitReturns
option rather than this rule. noImplicitReturns
is powered by TS's type information and control-flow analysis so it has better coverage than this rule.
- ❌ Incorrect
- ✅ Correct
function foo(): undefined {}
function bar(flag: boolean): undefined {
if (flag) return foo();
return;
}
async function baz(flag: boolean): Promise<undefined> {
if (flag) return;
return foo();
}
Open in Playgroundfunction foo(): void {}
function bar(flag: boolean): void {
if (flag) return foo();
return;
}
async function baz(flag: boolean): Promise<void | number> {
if (flag) return 42;
return;
}
Open in Playground选项
See eslint/consistent-return
's options.
如何使用
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"consistent-return": "off",
"@typescript-eslint/consistent-return": "error"
}
});
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"consistent-return": "off",
"@typescript-eslint/consistent-return": "error"
}
};
在线运行试试这个规则 ↗
何时不使用它
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.
'## 资源'
Taken with ❤️ from ESLint core.