Destructuring an Object
Explore how to efficiently extract variables from objects with destructuring in TypeScript. Understand techniques for renaming variables, setting default values, handling remaining properties, and using re-destructuring. This lesson helps you manipulate object data safely and cleanly.
Extract members with destructuring
Destructuring an object lets you create new variables from an existing object.
The syntax starts by using the curly bracket and the name of the destination variable. You can use many variables separated by commas. The name of the variable must be the name of the members you want to extract from the object.
Once the member selection is made, you need to close the curly bracket, use the equal sign, and write the name of the variable you want to destructure. In this scenario, like any variable, the use of let or const is used before starting.
Note that assigning a value to the destructured variable does not affect the original variable. On line 4, the value is multiplied by 100 and the value does not change on line 5.
Destructuring more than once
Re-destructuring requires avoiding defining the variable again. However, to use destructuring, you will have to surround the call with parentheses around the whole instruction.
Destructuring remaining variables
The second feature goes along with destructuring into variables. You can set specific variables from an object and indicate that all other members not assigned transfers into a new object. The transfer is done using the spread operator on the last variable of the left side on the assignment.
Renaming members while destructuring
A third feature is that you can name the new variables with something other than the name provided by the member of the original object while destructuring.
The same syntax of the first feature is used for renames, but with a small twist. The syntax changes by adding a colon after the variable and then the new name. Usually, after the colon, you can specify the name, but since you cannot change the name when destructuring, the new name is set instead.
On line 2 of the following code, the member destr1 is renamed to newName.
Destructuring and default values
Finally, when destructuring, you may stumble into a member that is optional. In this case, you want to ensure that you have a default value. To do so, after the name of the variable, use the equal sign, and set the desired default value. TypeScript won’t use the default value unless the value of the parameter is undefined.
On line 2, the string has a default value set to "default".
Destructuring an object is slightly more complex than an array because of the number of options. Nevertheless, destructuring an array is often used in languages like React where a portion of properties are needed. It allows for quick extraction of a specific set of members to be used directly in a function instead of always relying on the object name, followed by a dot and the name of the property.