版本

getter-return

强制 getter 中使用 return 语句

推荐

配置文件中使用 @eslint/jsrecommended 配置启用此规则

get 语法将对象属性绑定到一个函数,该函数将在查找该属性时被调用。它最初在 ECMAScript 5 中引入

const p = {
    get name(){
        return "nicholas";
    }
};

Object.defineProperty(p, "age", {
    get: function (){
        return 17;
    }
});

请注意,每个 getter 都应返回一个值。

规则详情

此规则强制要求属性 getter 中存在 return 语句。

此规则的错误代码示例

在 Playground 中打开
/*eslint getter-return: "error"*/

const p = {
    get name(){
        // no returns.
    }
};

Object.defineProperty(p, "age", {
    get: function (){
        // no returns.
    }
});

class P{
    get name(){
        // no returns.
    }
}

此规则的正确代码示例

在 Playground 中打开
/*eslint getter-return: "error"*/

const p = {
    get name(){
        return "nicholas";
    }
};

Object.defineProperty(p, "age", {
    get: function (){
        return 18;
    }
});

class P{
    get name(){
        return "nicholas";
    }
}

选项

此规则有一个对象选项

  • "allowImplicit": false(默认)不允许使用 return 语句隐式返回 undefined

{ "allowImplicit": true } 选项的正确代码示例

在 Playground 中打开
/*eslint getter-return: ["error", { allowImplicit: true }]*/
const p = {
    get name(){
        return; // return undefined implicitly.
    }
};

何时不使用

如果您的项目不使用 ES5 属性 getter,则不需要此规则。

由 TypeScript 处理

当使用 TypeScript 时,禁用此规则是安全的,因为 TypeScript 的编译器会强制执行此检查。

版本

此规则在 ESLint v4.2.0 中引入。

延伸阅读

资源

更改语言