prefer-destructuring
要求从数组和/或对象解构.
此规则报告的一些问题可通过 --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
- `eslint/prefer-destructuring`
- `@typescript-eslint/prefer-destructuring`
const x: string = obj.x; // This is incorrect and the auto fixer provides following untyped fix.
// const { x } = obj;
Open in Playgroundconst x: string = obj.x; // This is correct by default. You can also forbid this by an option.
Open in Playground借助类型检查器,它可以更准确地推断绑定模式。
¥And it infers binding patterns more accurately thanks to the type checker.
- ❌ 错误
- ✅ 正确
const x = ['a'];
const y = x[0];
Open in Playgroundconst x = { 0: 'a' };
const y = x[0];
Open in Playground当 enforceForRenamedProperties
不为真时,这是正确的。有效的解构语法被重命名为 { 0: y } = x
而不是 [y] = x
,因为 x
不可迭代。
¥It is correct when enforceForRenamedProperties
is not true.
Valid destructuring syntax is renamed style like { 0: y } = x
rather than [y] = x
because x
is not iterable.
如何使用
- 扁平配置
- 旧版配置
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"
}
});
module.exports = {
"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 Playgroundconst { x }: { x: string } = obj;
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.