no-empty-pattern
禁用空解构模式
✅ 推荐
在 配置文件 中使用来自 @eslint/js
的 recommended
配置启用此规则
当使用解构时,可能会创建一个没有效果的模式。当空花括号被用在嵌入对象解构模式的右侧时,就会发生这种情况,例如
// doesn't create any variables
const {a: {}} = foo;
在这段代码中,没有创建新的变量,因为 a
只是一个位置辅助,而 {}
应该包含要创建的变量,例如
// creates variable b
const {a: { b }} = foo;
在许多情况下,空对象模式是一个错误,作者本打算使用默认值,例如
// creates variable a
const {a = {}} = foo;
这两种模式之间的区别很微妙,尤其因为有问题的空模式看起来就像一个对象字面量。
规则详情
此规则旨在标记解构对象和数组中的任何空模式,因此,每当遇到空模式时,都会报告问题。
此规则的 错误 代码示例
在 Playground 中打开
/*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: }) {}
此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-empty-pattern: "error"*/
const {a = {}} = foo;
const {b = []} = foo;
function foo({a = {}}) {}
function bar({a = []}) {}
选项
此规则有一个对象选项用于例外情况
allowObjectPatternsAsParameters
默认设置为 false
。将此选项设置为 true
允许空对象模式作为函数参数。
注意: 此规则不允许空数组模式作为函数参数。
使用 {"allowObjectPatternsAsParameters": true}
选项时,此规则的 错误 代码示例
在 Playground 中打开
/*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}
选项时,此规则的 正确 代码示例
在 Playground 中打开
/*eslint no-empty-pattern: ["error", { "allowObjectPatternsAsParameters": true }]*/
function foo({}) {}
const bar = function({}) {};
const qux = ({}) => {};
function baz({} = {}) {}
版本
此规则在 ESLint v1.7.0 中引入。