Convert to destructuring assignment

Convert a variable declaration that accesses an object property to a destructuring assignment.

Convert to destructuring assignment

Why is this refactoring helpful?

The destructuring assignment syntax is more concise than the traditional property access and offers more clarity.

You can also declare several variables in a single destructuring assignment with a single evaluation of the source expression. Using destructuring assignments reduces code duplication and removes the need to extract an expensive source expression computation into a separate variable.

What do I need to consider?

TypeScript type information might need to be refined

In some cases, converting to destructuring can lead to errors on the type verification.

For example, consider the following snippet:

type ObjType = {
  [key: string]: string;
};

function f(obj: ObjType) {
  const property: string = obj.property;
}

Converting to destructuring would result in:

type ObjType = {
  [key: string]: string;
};

function f(obj: ObjType) {
  const { property }: { property: string } = obj;
}

However, it cannot be guaranteed that property exists on ObjType, and TypeScript shows an error.

This can be resolved by marking property as optional with ?:

type ObjType = {
  [key: string]: string;
};

function f(obj: ObjType) {
  const { property }: { property?: string } = obj;
}

Configuration

Related Code Assists

Learn More

Available In