Index

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
const {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
const {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
const {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"*/

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

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

🌐 Examples of correct code for this rule:

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

const {a = {}} = foo;
const {b = []} = 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.

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

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

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

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

function foo({a: {}}) {}
const bar = function({a: {}}) {};
const qux = ({a: {}}) => {};
const quux = ({} = bar) => {};
const item = ({} = { 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({}) {}
const bar = function({}) {};
const qux = ({}) => {};

function baz({} = {}) {}

版本

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

资源