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
- `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.
- ❌ Incorrect
- ✅ Correct
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.
如何使用
- Flat Config
- Legacy Config
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"
}
};
在线运行试试这个规则 ↗