From b3d80751788778cd471d58656150c7267d7cfd9e Mon Sep 17 00:00:00 2001 From: mdm317 Date: Wed, 30 Jul 2025 00:09:03 +0900 Subject: [PATCH 1/2] fix: Add logic when returning a union type. --- .../src/rules/prefer-return-this-type.ts | 9 +++++++++ .../tests/rules/prefer-return-this-type.test.ts | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts index 7d7b14044cfb..ef5733fd47ff 100644 --- a/packages/eslint-plugin/src/rules/prefer-return-this-type.ts +++ b/packages/eslint-plugin/src/rules/prefer-return-this-type.ts @@ -1,6 +1,7 @@ import type { TSESTree } from '@typescript-eslint/utils'; import { AST_NODE_TYPES } from '@typescript-eslint/utils'; +import { isUnionType } from 'ts-api-utils'; import * as ts from 'typescript'; import { createRule, forEachReturnStatement, getParserServices } from '../util'; @@ -116,6 +117,14 @@ export default createRule({ return; } + if ( + isUnionType(type) && + type.types.some(typePart => typePart === classType) + ) { + hasReturnClassType = true; + return true; + } + return; }); diff --git a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts index 5b372350059f..6e6cab78bc45 100644 --- a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts @@ -98,6 +98,19 @@ class Foo { ` class Foo { f?: string; +} + `, + ` +declare const valueUnion: BaseUnion | string; + +class BaseUnion { + f(): BaseUnion | string { + if (hidden) { + return this; + } + + return valueUnion; + } } `, ], From 602a349921fda458763c0bfbcebb76c56a439b14 Mon Sep 17 00:00:00 2001 From: mdm317 Date: Wed, 30 Jul 2025 00:16:11 +0900 Subject: [PATCH 2/2] test: add test --- .../rules/prefer-return-this-type.test.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts index 6e6cab78bc45..7d8748086bc0 100644 --- a/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts +++ b/packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts @@ -408,6 +408,42 @@ class Animal { console.log("I'm moving!"); return this; } +} + `, + }, + { + code: ` +declare const valueUnion: number | string; + +class BaseUnion { + f(): BaseUnion | string { + if (hidden) { + return this; + } + + return valueUnion; + } +} + `, + errors: [ + { + column: 8, + endColumn: 17, + line: 5, + messageId: 'useThisType', + }, + ], + output: ` +declare const valueUnion: number | string; + +class BaseUnion { + f(): this | string { + if (hidden) { + return this; + } + + return valueUnion; + } } `, },