Skip to main content

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.

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

How to Use

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"
}
});

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 }:

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

When 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.

Resources

Taken with ❤️ from ESLint core.