🌐 AI搜索 & 代理 主页
Skip to content
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
9 changes: 9 additions & 0 deletions packages/eslint-plugin/src/rules/prefer-return-this-type.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -116,6 +117,14 @@ export default createRule({
return;
}

if (
isUnionType(type) &&
type.types.some(typePart => typePart === classType)
) {
hasReturnClassType = true;
return true;
}

return;
});

Expand Down
49 changes: 49 additions & 0 deletions packages/eslint-plugin/tests/rules/prefer-return-this-type.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,19 @@ class Foo {
`
class Foo {
f?: string;
}
`,
`
declare const valueUnion: BaseUnion | string;

class BaseUnion {
f(): BaseUnion | string {
if (Math.random()) {
return this;
}

return valueUnion;
}
}
`,
],
Expand Down Expand Up @@ -395,6 +408,42 @@ class Animal<T> {
console.log("I'm moving!");
return this;
}
}
`,
},
{
code: `
declare const valueUnion: number | string;

class BaseUnion {
f(): BaseUnion | string {
if (Math.random()) {
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 (Math.random()) {
return this;
}

return valueUnion;
}
}
`,
},
Expand Down
Loading