メインコンテンツへスキップ

prefer-destructuring

配列やオブジェクトからの分割代入を必須とします。

🔧

このルールによって報告された一部の問題は、 --fix ESLint コマンドラインオプションで自動的に修正可能です。.

💭

このルールは、実行するために 型情報 が必要です。

このルールは、ベースの eslint/prefer-destructuring ルールを拡張します。変数宣言での TypeScript の型アノテーションのサポートが追加されます。

const x: string = obj.x; // This is incorrect and the auto fixer provides following untyped fix.
// const { x } = obj;
プレイグラウンドで開く

また、型チェッカーのおかげで、バインディングパターンをより正確に推論します。

const x = ['a'];
const y = x[0];
プレイグラウンドで開く

使い方

.eslintrc.cjs
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 のオプションを参照してください。

このルールは、以下のオプションを追加します。

type Options = [
BasePreferDestructuringOptions[0],
BasePreferDestructuringOptions[1] & {
enforceForDeclarationWithTypeAnnotation?: boolean;
},
];

const defaultOptions: Options = [
basePreferDestructuringDefaultOptions[0],
{
...basePreferDestructuringDefaultOptions[1],
enforceForDeclarationWithTypeAnnotation: false,
},
];

enforceForDeclarationWithTypeAnnotation

true に設定すると、型注釈付きの変数宣言は分割代入を使用することが強制されます。

{ enforceForDeclarationWithTypeAnnotation: true } を使用した例

const x: string = obj.x;
プレイグラウンドで開く

使用しない場合

型チェックされたリンター規則は、従来のリンター規則よりも強力ですが、型チェックされたリンティングの設定も必要です。型チェックされた規則を有効にした後にパフォーマンスの低下が発生する場合は、パフォーマンスのトラブルシューティングを参照してください。

リソース

ESLint coreから❤️を込めて引用。