Skip to content

Commit bd8ed8d

Browse files
fix(eslint-plugin): [prefer-return-this-type] don't report an error when returning a union type that includes a classType (#11432)
* fix: Add logic when returning a union type. * test: add test * Math.random() --------- Co-authored-by: Josh Goldberg <[email protected]>
1 parent d8ca5ef commit bd8ed8d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

packages/eslint-plugin/src/rules/prefer-return-this-type.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { TSESTree } from '@typescript-eslint/utils';
22

33
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
4+
import { isUnionType } from 'ts-api-utils';
45
import * as ts from 'typescript';
56

67
import { createRule, forEachReturnStatement, getParserServices } from '../util';
@@ -116,6 +117,14 @@ export default createRule({
116117
return;
117118
}
118119

120+
if (
121+
isUnionType(type) &&
122+
type.types.some(typePart => typePart === classType)
123+
) {
124+
hasReturnClassType = true;
125+
return true;
126+
}
127+
119128
return;
120129
});
121130

packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,19 @@ class Foo {
9898
`
9999
class Foo {
100100
f?: string;
101+
}
102+
`,
103+
`
104+
declare const valueUnion: BaseUnion | string;
105+
106+
class BaseUnion {
107+
f(): BaseUnion | string {
108+
if (Math.random()) {
109+
return this;
110+
}
111+
112+
return valueUnion;
113+
}
101114
}
102115
`,
103116
],
@@ -395,6 +408,42 @@ class Animal<T> {
395408
console.log("I'm moving!");
396409
return this;
397410
}
411+
}
412+
`,
413+
},
414+
{
415+
code: `
416+
declare const valueUnion: number | string;
417+
418+
class BaseUnion {
419+
f(): BaseUnion | string {
420+
if (Math.random()) {
421+
return this;
422+
}
423+
424+
return valueUnion;
425+
}
426+
}
427+
`,
428+
errors: [
429+
{
430+
column: 8,
431+
endColumn: 17,
432+
line: 5,
433+
messageId: 'useThisType',
434+
},
435+
],
436+
output: `
437+
declare const valueUnion: number | string;
438+
439+
class BaseUnion {
440+
f(): this | string {
441+
if (Math.random()) {
442+
return this;
443+
}
444+
445+
return valueUnion;
446+
}
398447
}
399448
`,
400449
},

0 commit comments

Comments
 (0)