Skip to content

fix(eslint-plugin): [no-unsafe-return] handle recursive type #10883

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

Merged
merged 3 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions packages/eslint-plugin/tests/rules/no-unsafe-return.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,17 @@ function foo(): Set<number> {
}
`,
'const foo: (() => void) | undefined = () => 1;',
`
class Foo {
public foo(): this {
return this;
}

protected then(resolve: () => void): void {
resolve();
}
}
`,
],
invalid: [
{
Expand Down
62 changes: 62 additions & 0 deletions packages/type-utils/src/discriminateAnyType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import type * as ts from 'typescript';

import * as tsutils from 'ts-api-utils';

import { isTypeAnyType, isTypeAnyArrayType } from './predicates';

export enum AnyType {
Any,
PromiseAny,
AnyArray,
Safe,
}
/**
* @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise<any>`,
* otherwise it returns `AnyType.Safe`.
*/
export function discriminateAnyType(
type: ts.Type,
checker: ts.TypeChecker,
program: ts.Program,
tsNode: ts.Node,
): AnyType {
return discriminateAnyTypeWorker(type, checker, program, tsNode, new Set());
}

function discriminateAnyTypeWorker(
type: ts.Type,
checker: ts.TypeChecker,
program: ts.Program,
tsNode: ts.Node,
visited: Set<ts.Type>,
) {
if (visited.has(type)) {
return AnyType.Safe;
}
visited.add(type);
if (isTypeAnyType(type)) {
return AnyType.Any;
}
if (isTypeAnyArrayType(type, checker)) {
return AnyType.AnyArray;
}
for (const part of tsutils.typeParts(type)) {
if (tsutils.isThenableType(checker, tsNode, part)) {
const awaitedType = checker.getAwaitedType(part);
if (awaitedType) {
const awaitedAnyType = discriminateAnyTypeWorker(
awaitedType,
checker,
program,
tsNode,
visited,
);
if (awaitedAnyType === AnyType.Any) {
return AnyType.PromiseAny;
}
}
}
}

return AnyType.Safe;
}
1 change: 1 addition & 0 deletions packages/type-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export * from './propertyTypes';
export * from './requiresQuoting';
export * from './typeFlagUtils';
export * from './TypeOrValueSpecifier';
export * from './discriminateAnyType';
export {
getDecorators,
getModifiers,
Expand Down
42 changes: 0 additions & 42 deletions packages/type-utils/src/predicates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,48 +108,6 @@ export function isTypeUnknownArrayType(
);
}

export enum AnyType {
Any,
PromiseAny,
AnyArray,
Safe,
}
/**
* @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise<any>`,
* otherwise it returns `AnyType.Safe`.
*/
export function discriminateAnyType(
type: ts.Type,
checker: ts.TypeChecker,
program: ts.Program,
tsNode: ts.Node,
): AnyType {
if (isTypeAnyType(type)) {
return AnyType.Any;
}
if (isTypeAnyArrayType(type, checker)) {
return AnyType.AnyArray;
}
for (const part of tsutils.typeParts(type)) {
if (tsutils.isThenableType(checker, tsNode, part)) {
const awaitedType = checker.getAwaitedType(part);
if (awaitedType) {
const awaitedAnyType = discriminateAnyType(
awaitedType,
checker,
program,
tsNode,
);
if (awaitedAnyType === AnyType.Any) {
return AnyType.PromiseAny;
}
}
}
}

return AnyType.Safe;
}

/**
* @returns Whether a type is an instance of the parent type, including for the parent's base types.
*/
Expand Down
101 changes: 101 additions & 0 deletions packages/type-utils/tests/discriminateAnyType.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { TSESTree } from '@typescript-eslint/typescript-estree';

import { parseForESLint } from '@typescript-eslint/parser';
import path from 'node:path';

import { AnyType, discriminateAnyType } from '../src';
import { expectToHaveParserServices } from './test-utils/expectToHaveParserServices';

type GetNode = (ast: TSESTree.Program) => TSESTree.Node;

describe('discriminateAnyType', () => {
const rootDir = path.join(__dirname, 'fixtures');

function getDeclarationId(ast: TSESTree.Program): TSESTree.Node {
const declaration = ast.body.at(-1) as TSESTree.VariableDeclaration;
const id = declaration.declarations[0].id;
return id;
}

function getTypes(code: string, getNode: GetNode) {
const { ast, services } = parseForESLint(code, {
disallowAutomaticSingleRunInference: true,
filePath: path.join(rootDir, 'file.ts'),
project: './tsconfig.json',
tsconfigRootDir: rootDir,
});
expectToHaveParserServices(services);
const node = getNode(ast);
const type = services.getTypeAtLocation(getNode(ast));
return {
checker: services.program.getTypeChecker(),
program: services.program,
tsNode: services.esTreeNodeToTSNodeMap.get(node),
type,
};
}

function runTest(
code: string,
expected: AnyType,
getNode: GetNode = getDeclarationId,
): void {
const { checker, program, tsNode, type } = getTypes(code, getNode);
const result = discriminateAnyType(type, checker, program, tsNode);
expect(result).toBe(expected);
}

describe('returns Safe', () => {
it.each([
['const foo = "foo";', AnyType.Safe],
['const foo = 1;', AnyType.Safe],
['const foo = [1, 2];', AnyType.Safe],
])('when code is %s, returns %s', runTest);

it('should returns Safe for a recursive thenable.', () => {
const code = `
class Foo {
foo() {
return this;
}
protected then(resolve: () => void): void {
resolve();
}
};
`;
runTest(code, AnyType.Safe, ast => {
const classDeclration = ast.body[0] as TSESTree.ClassDeclaration;
const method = classDeclration.body
.body[0] as TSESTree.MethodDefinition;
const returnStatement = method.value.body?.body.at(
-1,
) as TSESTree.ReturnStatement;
return returnStatement.argument!;
});
});
});

describe('returns Any', () => {
it.each([
['const foo = 1 as any;', AnyType.Any],
['let foo;', AnyType.Any],
])('when code is %s, returns %s', runTest);
});

describe('returns PromiseAny', () => {
it.each([
['const foo = Promise.resolve({} as any);', AnyType.PromiseAny],
[
'const foo = Promise.resolve(Promise.resolve({} as any));',
AnyType.PromiseAny,
],
])('when code is %s, returns %s', runTest);
});

describe('returns AnyArray', () => {
it.each([
['const foo = [{} as any];', AnyType.AnyArray],
['const foo = [{} as any, 2];', AnyType.AnyArray],
])('when code is %s, returns %s', runTest);
});
});