related-getter-setter-pairs
Enforce that
get()
types should be assignable to their equivalentset()
type.
Extending "plugin:@typescript-eslint/strict-type-checked"
in an ESLint configuration enables this rule.
This rule requires type information to run.
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:
// 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.
- Flat Config
- Legacy Config
export default tseslint.config({
rules: {
"@typescript-eslint/related-getter-setter-pairs": "error"
}
});
module.exports = {
"rules": {
"@typescript-eslint/related-getter-setter-pairs": "error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
interface Box {
get value(): string;
set value(newValue: number);
}
Open in Playgroundinterface Box {
get value(): string;
set value(newValue: string);
}
Open in PlaygroundOptions
This rule is not configurable.
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 for those specific situations instead of completely disabling this rule.
Further Reading
- MDN documentation on
get
- MDN documentation on
set
- TypeScript 5.1 Release Notes > Unrelated Types for Getters and Setters
Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.
See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.