Skip to main content

prefer-destructuring

Require destructuring from arrays and/or objects.

🔧

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

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

🧱

This is an "extension" rule that replaces a core ESLint rule to work with TypeScript. See Rules > Extension Rules.

This rule extends the base prefer-destructuring rule from ESLint core. 它在变量声明中添加了对 TypeScript 类型注释的支持。

¥It adds support for TypeScript's type annotations in variable declarations.

示例

¥Examples

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

如何使用

eslint.config.mjs
export default tseslint.config({
rules: {
// Note: you must disable the base rule as it can report incorrect errors
"prefer-destructuring": "off",
"@typescript-eslint/prefer-destructuring": "error"
}
});

在线运行试试这个规则 ↗

选项

See eslint/prefer-destructuring's options.

¥Options

该规则添加了以下选项:

¥This rule adds the following options:

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

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

enforceForDeclarationWithTypeAnnotation

带有 { enforceForDeclarationWithTypeAnnotation: true } 的示例:

¥Examples with { enforceForDeclarationWithTypeAnnotation: true }:

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

何时不使用它

Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

'## 资源'

Taken with ❤️ from ESLint core.