Destructuring a type and an array

Destructuring is a feature of JavaScript that is supported by TypeScript with type protection. Destructuring breaks an object into different pieces. TypeScript brings the type to these pieces.

A scenario is that you need to extract members from an object into a variable. This can be done without destructuring, but it takes several lines of code:

interface MyObject {
id: number;
time: number;
name: string;
startTime: Date;
stopTime: Date;
category: string;
}

const obj: MyObject = {
id: 1,
time: 100,
name: "MyName",
startTime: new Date(),
stopTime: new Date(),
category: "Cat5"
};

const id = obj.id;
const name = obj.name;
const category = obj.category;

With destructuring, it can be done in a single line. All the variables are from the type of the object. It means that id is a new variable of type number, name is of the type string, as well as category:

const { id, name, category } = obj;

Destructuring can use the rest operator to take the remainder of the properties not specified. The rest of the syntax is the three dots before the name of the variable that will hold the rest of the members:

const { id, name, category, ...remainingMembers } = obj;

remainingMembers.startTime;
remainingMembers.stopTime;
remainingMembers.time;

As you can see, the variable remainingMember has three members that are the three members not explicitly called out before the rest. It means that the type of remainingMember is an object literal with a member startTime, stopTime and time of type Date, Date, and number.

Destructuring and rest also work with an array. You can specify a variable name that will be of the type of the array. The rest allows creating a new array with the remainder of the value with the type of the initial array. In the following code example, the value1 contains the number 1 (not a string but as a number). The value2 contains 2, and value3To9 is an array with the values 3, 4, 5, 6, 7, 8, and 9:

 const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const [value1, value2, ...value3To9] = values;

It is also possible to skip position by using a comma without specifying a variable. In the following code example, there is a space between  value_1 and value_2, which means that the value at the second position, which is 2, is not in any individual variable (value1 or value2), neither is in the variable value4To9:

const values = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const [value1, value2, ...value3To9] = values;
const [value_1, , value_3, ...value4To9] = values;
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.118.14