Skip to main content

related-getter-setter-pairs

Enforce that get() types should be assignable to their equivalent set() type.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

TypeScript 允许为 get 参数及其对应的 set 返回定义不同的类型。在 TypeScript 4.3 之前,类型必须相同。从 TypeScript 4.3 到 5.0,get 类型必须是 set 类型的子类型。从 TypeScript 5.1 开始,只要有明确的类型注释,类型可能完全不相关。

¥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.

getset 对定义截然不同的类型可能会造成混淆。这意味着将属性分配给自身不起作用:

¥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;

此规则报告任何 get() 运算符,其参数已经是 set()get() 类型。

¥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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/related-getter-setter-pairs": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

interface Box {
get value(): string;
set value(newValue: number);
}
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你的项目需要对数据之间的不寻常关系进行建模,例如较旧的 DOM 类型,则此规则可能对你没有用。你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

¥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


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.

'## 资源'