Skip to main content

prefer-destructuring

Require destructuring from arrays and/or objects.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行。


示例

此规则扩展了基本 eslint/prefer-destructuring 规则。 它在变量声明中添加了对 TypeScript 类型注释的支持。

英:This rule extends the base eslint/prefer-destructuring rule. It adds support for TypeScript's type annotations in variable declarations.

const x: string = obj.x; // This is incorrect and the auto fixer provides following untyped fix.
// const { x } = obj;
Open in Playground

借助类型检查器,它可以更准确地推断绑定模式。

英:And it infers binding patterns more accurately thanks to the type checker.

const x = ['a'];
const y = x[0];
Open in Playground

选项

该规则添加了以下选项:

英:This rule adds the following options:

type Options = [
BasePreferDestructuringOptions[0],
BasePreferDestructuringOptions[1] & {
enforceForDeclarationWithTypeAnnotation?: boolean;
},
];

const defaultOptions: Options = [
basePreferDestructuringDefaultOptions[0],
{
...basePreferDestructuringDefaultOptions[1],
enforceForDeclarationWithTypeAnnotation: false,
},
];

enforceForDeclarationWithTypeAnnotation

当设置为 true 时,强制类型注释变量声明使用解构赋值。

英:When set to true, type annotated variable declarations are enforced to use destructuring assignment.

{ enforceForDeclarationWithTypeAnnotation: true } 的示例:

英:Examples with { enforceForDeclarationWithTypeAnnotation: true }:

const x: string = obj.x;
Open in Playground

如何使用

.eslintrc.cjs
module.exports = {
"rules": {
// Note: you must disable the base rule as it can report incorrect errors
"prefer-destructuring": "off",
"@typescript-eslint/prefer-destructuring": "error"
}
};
在线运行试试这个规则 ↗

选项

参见 eslint/prefer-destructuring 选项

资源

摘自 ❤️ ESLint 内核