prefer-destructuring
Require destructuring from arrays and/or objects.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
This rule requires type information to run.
Examples
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 PlaygroundAnd 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 PlaygroundIt 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.
How to Use
- 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"
}
};
Try this rule in the playground ↗
Options
See eslint/prefer-destructuring
's 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
Examples with { enforceForDeclarationWithTypeAnnotation: true }
:
- ❌ Incorrect
- ✅ Correct
const x: string = obj.x;
Open in Playgroundconst { x }: { x: string } = obj;
Open in PlaygroundWhen Not To Use It
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.