no-empty-pattern

不允许空解构模式

Recommended

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

使用解构时,可以创建没有效果的模式。当嵌入对象解构模式的右侧使用空大括号时,会发生这种情况,例如:

¥When using destructuring, it’s possible to create a pattern that has no effect. This happens when empty curly braces are used to the right of an embedded object destructuring pattern, such as:

// doesn't create any variables
var {a: {}} = foo;

在这段代码中,没有创建新变量,因为 a 只是一个位置助手,而 {} 应该包含要创建的变量,例如:

¥In this code, no new variables are created because a is just a location helper while the {} is expected to contain the variables to create, such as:

// creates variable b
var {a: { b }} = foo;

在许多情况下,空对象模式是作者打算使用默认值来代替的错误,例如:

¥In many cases, the empty object pattern is a mistake where the author intended to use a default value instead, such as:

// creates variable a
var {a = {}} = foo;

这两种模式之间的区别是微妙的,特别是因为有问题的空模式看起来就像一个对象字面量。

¥The difference between these two patterns is subtle, especially because the problematic empty pattern looks just like an object literal.

规则详情

¥Rule Details

此规则旨在标记解构对象和数组中的任何空模式,因此,只要遇到问题就会报告问题。

¥This rule aims to flag any empty patterns in destructured objects and arrays, and as such, will report a problem whenever one is encountered.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-empty-pattern: "error"*/

var {} = foo;
var [] = foo;
var {a: {}} = foo;
var {a: []} = foo;
function foo({}) {}
function bar([]) {}
function baz({a: {}}) {}
function qux({a: []}) {}

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-empty-pattern: "error"*/

var {a = {}} = foo;
var {a = []} = foo;
function foo({a = {}}) {}
function bar({a = []}) {}

选项

¥Options

此规则有一个异常对象选项:

¥This rule has an object option for exceptions:

allowObjectPatternsAsParameters

默认设置为 false。将此选项设置为 true 允许空对象模式作为函数参数。

¥Set to false by default. Setting this option to true allows empty object patterns as function parameters.

注意:此规则不允许空数组模式作为函数参数。

¥Note: This rule doesn’t allow empty array patterns as function parameters.

使用 {"allowObjectPatternsAsParameters": true} 选项的此规则的错误代码示例:

¥Examples of incorrect code for this rule with the {"allowObjectPatternsAsParameters": true} option:

在线运行
/*eslint no-empty-pattern: ["error", { "allowObjectPatternsAsParameters": true }]*/

function foo({a: {}}) {}
var bar = function({a: {}}) {};
var bar = ({a: {}}) => {};
var bar = ({} = bar) => {};
var bar = ({} = { bar: 1 }) => {};

function baz([]) {}

使用 {"allowObjectPatternsAsParameters": true} 选项的此规则的正确代码示例:

¥Examples of correct code for this rule with the {"allowObjectPatternsAsParameters": true} option:

在线运行
/*eslint no-empty-pattern: ["error", { "allowObjectPatternsAsParameters": true }]*/

function foo({}) {}
var bar = function({}) {};
var bar = ({}) => {};

function baz({} = {}) {}

版本

此规则是在 ESLint v1.7.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号