Index

getter-return

在 getter 中执行 return 语句

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

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

🌐 The get syntax binds an object property to a function that will be called when that property is looked up. It was first introduced in ECMAScript 5:

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

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

请注意,每个 getter 都预计会返回一个值。

🌐 Note that every getter is expected to return a value.

规则详情

🌐 Rule Details

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

🌐 This rule enforces that a return statement is present in property getters.

此规则的错误代码示例:

🌐 Examples of incorrect code for this rule:

在线运行
/*eslint getter-return: "error"*/

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

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

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

符合此规则的正确代码示例:

🌐 Examples of correct code for this rule:

在线运行
/*eslint getter-return: "error"*/

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

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

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

选项

🌐 Options

此规则有一个对象选项:

🌐 This rule has an object option:

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

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

🌐 Examples of correct code for the { "allowImplicit": true } option:

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

何时不使用

🌐 When Not To Use It

如果你的项目不使用 ES5 属性获取器,则不需要此规则。

🌐 If your project will not be using ES5 property getters you do not need this rule.

由 TypeScript 处理

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

版本

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

进阶读物

资源