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 7d7b14044cf..ef5733fd47f 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 5b372350059..7d8748086bc 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; + } } `, ], @@ -395,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; + } } `, }, pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy