Skip to main content

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. 它增加了对返回 voidPromise<void> 的函数的支持。

¥It adds support for functions that return void or Promise<void>.

warning

如果可能,建议使用 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.

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 Playground

选项

See eslint/consistent-return's options.

如何使用

eslint.config.mjs
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"
}
});

在线运行试试这个规则 ↗

何时不使用它

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.