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.
- 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.
选项
该规则添加了以下选项:
英: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 Playgroundconst { x }: { x: string } = obj;
Open in Playground如何使用
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 内核