版本

no-empty-pattern

不允許空的解構模式

推薦

設定檔中使用來自 @eslint/jsrecommended 設定,即可啟用此規則

當使用解構時,有可能建立一個沒有效果的模式。當在嵌入式物件解構模式的右側使用空的大括號時,就會發生這種情況,例如

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

在這段程式碼中,沒有建立新的變數,因為 a 只是一個位置輔助,而 {} 預期包含要建立的變數,例如

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

在許多情況下,空的物件模式是一個錯誤,作者本意是使用預設值,例如

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

這兩種模式之間的差異很細微,特別是因為有問題的空模式看起來就像一個物件字面值。

規則詳情

此規則旨在標記解構物件和陣列中的任何空模式,因此,每當遇到空模式時,都會報告問題。

此規則的錯誤程式碼範例

在測試區開啟
/*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: []}) {}

此規則的正確程式碼範例

在測試區開啟
/*eslint no-empty-pattern: "error"*/

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

選項

此規則有一個物件選項用於例外情況

allowObjectPatternsAsParameters

預設設為 false。將此選項設定為 true 允許空的物件模式作為函式參數。

注意:此規則不允許空的陣列模式作為函式參數。

此規則搭配 {"allowObjectPatternsAsParameters": true} 選項的錯誤程式碼範例

在測試區開啟
/*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} 選項的正確程式碼範例

在測試區開啟
/*eslint no-empty-pattern: ["error", { "allowObjectPatternsAsParameters": true }]*/

function foo({}) {}
const bar = function({}) {};
const qux = ({}) => {};

function baz({} = {}) {}

版本

此規則在 ESLint v1.7.0 中引入。

資源

變更語言