no-setter-return
禁止从 setter 返回值
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
Setter 不能返回值。
🌐 Setters cannot return values.
虽然从 setter 返回值不会产生错误,但返回的值会被忽略。因此,从 setter 返回值要么是不必要的,要么可能是一个错误,因为返回的值无法使用。
🌐 While returning a value from a setter does not produce an error, the returned value is being ignored. Therefore, returning a value from a setter is either unnecessary or a possible error, since the returned value cannot be used.
规则详情
🌐 Rule Details
此规则不允许从 setter 返回值,并报告 setter 函数中的 return 语句。
🌐 This rule disallows returning values from setters and reports return statements in setter functions.
只有没有值的 return 是允许的,因为它是一个控制流语句。
🌐 Only return without a value is allowed, as it’s a control flow statement.
此规则检查设置器:
🌐 This rule checks setters in:
- 对象字面量。
- 类声明和类表达式。
- 全局对象的
Object.create、Object.defineProperty、Object.defineProperties和Reflect.defineProperty方法中的属性描述符。
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-setter-return: "error"*/
const foo = {
set a(value) {
this.val = value;
return value;
}
};
class Foo {
set a(value) {
this.val = value * 2;
return this.val;
}
}
const Bar = class {
static set a(value) {
if (value < 0) {
this.val = 0;
return 0;
}
this.val = value;
}
};
Object.defineProperty(foo, "bar", {
set(value) {
if (value < 0) {
return false;
}
this.val = value;
}
});
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-setter-return: "error"*/
const foo = {
set a(value) {
this.val = value;
}
};
class Foo {
set a(value) {
this.val = value * 2;
}
}
const Bar = class {
static set a(value) {
if (value < 0) {
this.val = 0;
return;
}
this.val = value;
}
};
Object.defineProperty(foo, "bar", {
set(value) {
if (value < 0) {
throw new Error("Negative value.");
}
this.val = value;
}
});
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
相关规则
版本
此规则是在 ESLint v6.7.0 中引入。