Skip to content

feat(eslint-plugin): added related-getter-setter-pairs rule #10192

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
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
61 changes: 61 additions & 0 deletions packages/eslint-plugin/docs/rules/related-getter-setter-pairs.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
---
description: 'Enforce that `get()` types should be assignable to their equivalent `set()` type.'
---

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

> 🛑 This file is source code, not the primary documentation location! 🛑
>
> See **https://typescript-eslint.io/rules/related-getter-setter-pairs** for documentation.

TypeScript allows defining different types for a `get` parameter and its corresponding `set` return.
Prior to TypeScript 4.3, the types had to be identical.
From TypeScript 4.3 to 5.0, the `get` type had to be a subtype of the `set` type.
As of TypeScript 5.1, the types may be completely unrelated as long as there is an explicit type annotation.

Defining drastically different types for a `get` and `set` pair can be confusing.
It means that assigning a property to itself would not work:

```ts
// Assumes box.value's get() return is assignable to its set() parameter
box.value = box.value;
```

This rule reports cases where a `get()` and `set()` have the same name, but the `get()`'s type is not assignable to the `set()`'s.

## Examples

<Tabs>
<TabItem value="❌ Incorrect">

```ts
interface Box {
get value(): string;
set value(newValue: number);
}
```

</TabItem>
<TabItem value="✅ Correct">

```ts
interface Box {
get value(): string;
set value(newValue: string);
}
```

</TabItem>
</Tabs>

## When Not To Use It

If your project needs to model unusual relationships between data, such as older DOM types, this rule may not be useful for you.
You might consider using [ESLint disable comments](https://eslint.org/docs/latest/use/configure/rules#using-configuration-comments-1) for those specific situations instead of completely disabling this rule.

## Further Reading

- [MDN documentation on `get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)
- [MDN documentation on `set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set)
- [TypeScript 5.1 Release Notes > Unrelated Types for Getters and Setters](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-1.html#unrelated-types-for-getters-and-setters)
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export = {
'@typescript-eslint/prefer-return-this-type': 'error',
'@typescript-eslint/prefer-string-starts-ends-with': 'error',
'@typescript-eslint/promise-function-async': 'error',
'@typescript-eslint/related-getter-setter-pairs': 'error',
'@typescript-eslint/require-array-sort-compare': 'error',
'require-await': 'off',
'@typescript-eslint/require-await': 'error',
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin/src/configs/disable-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export = {
'@typescript-eslint/prefer-return-this-type': 'off',
'@typescript-eslint/prefer-string-starts-ends-with': 'off',
'@typescript-eslint/promise-function-async': 'off',
'@typescript-eslint/related-getter-setter-pairs': 'off',
'@typescript-eslint/require-array-sort-compare': 'off',
'@typescript-eslint/require-await': 'off',
'@typescript-eslint/restrict-plus-operands': 'off',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export = {
'@typescript-eslint/prefer-promise-reject-errors': 'error',
'@typescript-eslint/prefer-reduce-type-parameter': 'error',
'@typescript-eslint/prefer-return-this-type': 'error',
'@typescript-eslint/related-getter-setter-pairs': 'error',
'require-await': 'off',
'@typescript-eslint/require-await': 'error',
'@typescript-eslint/restrict-plus-operands': [
Expand Down
3 changes: 2 additions & 1 deletion packages/eslint-plugin/src/configs/strict-type-checked.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export = {
'@typescript-eslint/prefer-promise-reject-errors': 'error',
'@typescript-eslint/prefer-reduce-type-parameter': 'error',
'@typescript-eslint/prefer-return-this-type': 'error',
'@typescript-eslint/related-getter-setter-pairs': 'error',
'require-await': 'off',
'@typescript-eslint/require-await': 'error',
'@typescript-eslint/restrict-plus-operands': [
Expand All @@ -93,10 +94,10 @@ export = {
{
allowAny: false,
allowBoolean: false,
allowNever: false,
allowNullish: false,
allowNumber: false,
allowRegExp: false,
allowNever: false,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤷

},
],
'no-return-await': 'off',
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/src/rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ import preferReturnThisType from './prefer-return-this-type';
import preferStringStartsEndsWith from './prefer-string-starts-ends-with';
import preferTsExpectError from './prefer-ts-expect-error';
import promiseFunctionAsync from './promise-function-async';
import relatedGetterSetterPairs from './related-getter-setter-pairs';
import requireArraySortCompare from './require-array-sort-compare';
import requireAwait from './require-await';
import restrictPlusOperands from './restrict-plus-operands';
Expand Down Expand Up @@ -244,6 +245,7 @@ const rules = {
'prefer-string-starts-ends-with': preferStringStartsEndsWith,
'prefer-ts-expect-error': preferTsExpectError,
'promise-function-async': promiseFunctionAsync,
'related-getter-setter-pairs': relatedGetterSetterPairs,
'require-array-sort-compare': requireArraySortCompare,
'require-await': requireAwait,
'restrict-plus-operands': restrictPlusOperands,
Expand Down
113 changes: 113 additions & 0 deletions packages/eslint-plugin/src/rules/related-getter-setter-pairs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import type { TSESTree } from '@typescript-eslint/utils';

import { AST_NODE_TYPES } from '@typescript-eslint/utils';

import { createRule, getNameFromMember, getParserServices } from '../util';

type Method = TSESTree.MethodDefinition | TSESTree.TSMethodSignature;

type GetMethod = {
kind: 'get';
returnType: TSESTree.TSTypeAnnotation;
} & Method;

type GetMethodRaw = {
returnType: TSESTree.TSTypeAnnotation | undefined;
} & GetMethod;

type SetMethod = { kind: 'set'; params: [TSESTree.Node] } & Method;

interface MethodPair {
get?: GetMethod;
set?: SetMethod;
}

export default createRule({
name: 'related-getter-setter-pairs',
meta: {
type: 'problem',
docs: {
description:
'Enforce that `get()` types should be assignable to their equivalent `set()` type',
recommended: 'strict',
requiresTypeChecking: true,
},
messages: {
mismatch:
'`get()` type should be assignable to its equivalent `set()` type.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = getParserServices(context);
const checker = services.program.getTypeChecker();
const methodPairsStack: Map<string, MethodPair>[] = [];

function addPropertyNode(
member: GetMethod | SetMethod,
inner: TSESTree.Node,
kind: 'get' | 'set',
): void {
const methodPairs = methodPairsStack[methodPairsStack.length - 1];
const { name } = getNameFromMember(member, context.sourceCode);

methodPairs.set(name, {
...methodPairs.get(name),
[kind]: inner,
});
}

return {
':matches(ClassBody, TSInterfaceBody, TSTypeLiteral):exit'(): void {
const methodPairs = methodPairsStack[methodPairsStack.length - 1];

for (const pair of methodPairs.values()) {
if (!pair.get || !pair.set) {
continue;
}

const getter = pair.get;

const getType = services.getTypeAtLocation(getter);
const setType = services.getTypeAtLocation(pair.set.params[0]);

if (!checker.isTypeAssignableTo(getType, setType)) {
context.report({
node: getter.returnType.typeAnnotation,
messageId: 'mismatch',
});
}
}

methodPairsStack.pop();
},
':matches(MethodDefinition, TSMethodSignature)[kind=get]'(
node: GetMethodRaw,
): void {
const getter = getMethodFromNode(node);

if (getter.returnType) {
addPropertyNode(node, getter, 'get');
}
},
':matches(MethodDefinition, TSMethodSignature)[kind=set]'(
node: SetMethod,
): void {
const setter = getMethodFromNode(node);

if (setter.params.length === 1) {
addPropertyNode(node, setter, 'set');
}
},

'ClassBody, TSInterfaceBody, TSTypeLiteral'(): void {
methodPairsStack.push(new Map());
},
};
},
});

function getMethodFromNode(node: GetMethodRaw | SetMethod) {
return node.type === AST_NODE_TYPES.TSMethodSignature ? node : node.value;
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading