Techscrypt

Using object de-structuring with typescript

javascript

ES6 comes with a feature called object destructuring

Here is how it works:

const person = {
fName: "Homer",
lName: "Simpson",
age: 45,
height: 5.2,
};

const { fName, age } = person;
console.log(fName); // "Homer"
console.log(age); // 45

// Essentially, this replaces

const fName = person.fName;
const age = person.age;

// And shortens multiple lines of variable delarations into one concise variable declaration

In order to use this kind of syntax with typescript, we want to specify types for each of the de-structured variables.

const { var1, var2 }: { var1: type1, var2: type2 } = object;

Here is how we can re-write the above code snippet using typescript:

const person = {
fName: "Homer",
lName: "Simpson",
age: 45,
height: 5.2,
};

// What we would like to implement is this:
const fn: string = person.fName;
const ag: number = person.age;

// Using typescript, we can do it this way:
const { fName, age }: { fName: string, age: number } = person;
console.log(fName); // "Homer"
console.log(age); // 45

Subscribe to the Newsletter

We will only use your email address to send out the weekly newsletter with the latest updates from Techscrypt.

* indicates required