Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(eslint-plugin): [consistent-return] add new rule #8289

Merged
merged 21 commits into from Feb 23, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/eslint-plugin/docs/rules/consistent-return.md
@@ -0,0 +1,32 @@
---
description: 'Require `return` statements to either always or never specify values.'
---

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/consistent-return** for documentation.

This rule extends the base [`eslint/consistent-return`](https://eslint.org/docs/rules/consistent-return) rule.
This version adds support for functions that return void type.
yeonjuan marked this conversation as resolved.
Show resolved Hide resolved

<!--tabs-->

### ❌ Incorrect

```ts
function foo(): undefined {}
function bar(flag: boolean): undefined {
if (flag) return foo();
return;
}
```

### ✅ Correct

```ts
function foo(): void {}
function bar(flag: boolean): void {
if (flag) return foo();
return;
}
```
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/configs/all.ts
Expand Up @@ -19,6 +19,8 @@ export = {
'@typescript-eslint/class-methods-use-this': 'error',
'@typescript-eslint/consistent-generic-constructors': 'error',
'@typescript-eslint/consistent-indexed-object-style': 'error',
'consistent-return': 'off',
'@typescript-eslint/consistent-return': 'error',
'@typescript-eslint/consistent-type-assertions': 'error',
'@typescript-eslint/consistent-type-definitions': 'error',
'@typescript-eslint/consistent-type-exports': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/disable-type-checked.ts
Expand Up @@ -9,6 +9,7 @@ export = {
parserOptions: { project: null, program: null },
rules: {
'@typescript-eslint/await-thenable': 'off',
'@typescript-eslint/consistent-return': 'off',
'@typescript-eslint/consistent-type-exports': 'off',
'@typescript-eslint/dot-notation': 'off',
'@typescript-eslint/naming-convention': 'off',
Expand Down
117 changes: 117 additions & 0 deletions packages/eslint-plugin/src/rules/consistent-return.ts
@@ -0,0 +1,117 @@
import { type TSESTree } from '@typescript-eslint/utils';
import * as tsutils from 'ts-api-utils';
import * as ts from 'typescript';

import type {
InferMessageIdsTypeFromRule,
InferOptionsTypeFromRule,
} from '../util';
import { createRule, getParserServices, isTypeFlagSet } from '../util';
import { getESLintCoreRule } from '../util/getESLintCoreRule';

const baseRule = getESLintCoreRule('consistent-return');

type Options = InferOptionsTypeFromRule<typeof baseRule>;
type MessageIds = InferMessageIdsTypeFromRule<typeof baseRule>;

type FunctionNode =
| TSESTree.FunctionDeclaration
| TSESTree.FunctionExpression
| TSESTree.ArrowFunctionExpression;

export default createRule<Options, MessageIds>({
name: 'consistent-return',
meta: {
type: 'suggestion',
docs: {
description:
'Require `return` statements to either always or never specify values',
extendsBaseRule: true,
requiresTypeChecking: true,
},
hasSuggestions: baseRule.meta.hasSuggestions,
schema: baseRule.meta.schema,
messages: baseRule.meta.messages,
},
defaultOptions: [],
create(context) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
const rules = baseRule.create(context);
const functions: FunctionNode[] = [];

function enterFunction(node: FunctionNode): void {
functions.push(node);
}

function exitFunction(): void {
functions.pop();
}

function getCurrentFunction(): FunctionNode | null {
return functions[functions.length - 1] ?? null;
}

function isReturnPromiseVoid(
node: FunctionNode,
signature: ts.Signature,
): boolean {
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
const returnType = signature.getReturnType();
if (
tsutils.isThenableType(checker, tsNode, returnType) &&
tsutils.isTypeReference(returnType)
) {
const typeArgs = returnType.typeArguments;
const hasVoid = !!typeArgs?.some(typeArg =>
isTypeFlagSet(typeArg, ts.TypeFlags.Void),
);
return hasVoid;
}
return false;
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
}

function isReturnVoidOrThenableVoid(node: FunctionNode): boolean {
const functionType = services.getTypeAtLocation(node);
const callSignatures = functionType.getCallSignatures();
yeonjuan marked this conversation as resolved.
Show resolved Hide resolved

return callSignatures.some(signature => {
if (node.async) {
return isReturnPromiseVoid(node, signature);
}
const returnType = signature.getReturnType();
return isTypeFlagSet(returnType, ts.TypeFlags.Void);
});
}

return {
...rules,
FunctionDeclaration: enterFunction,
'FunctionDeclaration:exit'(node): void {
exitFunction();
rules['FunctionDeclaration:exit'](node);
},
FunctionExpression: enterFunction,
'FunctionExpression:exit'(node): void {
exitFunction();
rules['FunctionExpression:exit'](node);
},
ArrowFunctionExpression: enterFunction,
'ArrowFunctionExpression:exit'(node): void {
exitFunction();
rules['ArrowFunctionExpression:exit'](node);
},
ReturnStatement(node): void {
const functionNode = getCurrentFunction();
if (
!node.argument &&
functionNode &&
isReturnVoidOrThenableVoid(functionNode)
) {
return;
}
rules.ReturnStatement(node);
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
},
};
},
});
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Expand Up @@ -12,6 +12,7 @@ import commaDangle from './comma-dangle';
import commaSpacing from './comma-spacing';
import consistentGenericConstructors from './consistent-generic-constructors';
import consistentIndexedObjectStyle from './consistent-indexed-object-style';
import consistentReturn from './consistent-return';
import consistentTypeAssertions from './consistent-type-assertions';
import consistentTypeDefinitions from './consistent-type-definitions';
import consistentTypeExports from './consistent-type-exports';
Expand Down Expand Up @@ -153,6 +154,7 @@ export default {
'comma-spacing': commaSpacing,
'consistent-generic-constructors': consistentGenericConstructors,
'consistent-indexed-object-style': consistentIndexedObjectStyle,
'consistent-return': consistentReturn,
'consistent-type-assertions': consistentTypeAssertions,
'consistent-type-definitions': consistentTypeDefinitions,
'consistent-type-exports': consistentTypeExports,
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/util/getESLintCoreRule.ts
Expand Up @@ -6,6 +6,7 @@ const isESLintV8 = semver.major(version) >= 8;

interface RuleMap {
/* eslint-disable @typescript-eslint/consistent-type-imports -- more concise to use inline imports */
'consistent-return': typeof import('eslint/lib/rules/consistent-return');
JoshuaKGoldberg marked this conversation as resolved.
Show resolved Hide resolved
'arrow-parens': typeof import('eslint/lib/rules/arrow-parens');
'block-spacing': typeof import('eslint/lib/rules/block-spacing');
'brace-style': typeof import('eslint/lib/rules/brace-style');
Expand Down