DEV Community

Cover image for Destructuring using 'this' keyword at Typescript
Loukas Kotas
Loukas Kotas

Posted on

Destructuring using 'this' keyword at Typescript

Object Destructuring

Object Destructuring introduced at ES6 and it's useful for object assignment value-by-value.

Example

const {a1: string, a2: string} = {greeting: 'Hello!', who: 'dev.to Community'};
// a1: 'Hello1',
// a2: 'Dev To Community',
Enter fullscreen mode Exit fullscreen mode

The Problem

class DevToClass {
  a1: string;
  a2: string;
  a3: string;

setVal(): void {
  // error: 'this' is not recognized inside the scope. 
  const {this.a1, this.a2, this.a3} = {a1: 'Hello!', a2: 'dev.to', a3: 'community'};
}
}
Enter fullscreen mode Exit fullscreen mode

The Case

Imagine the scenario we have a class, and we want to assign some object's values, that can also be undefined to a class's variables.
Typescript will complain that this is not recognized. So we have to assign those variables to some constants and then assign them to class's variables.

class DevToClass {
  a1: string;
  a2: string;
  a3: string;

setVal(): void {
  const {a1, a2, a3} = {a1: 'Hello!', a2: 'dev.to', a3: 'community'};
  this.a1 = a1;
  this.a2 = a2;
  this.a3 = a3; 
}
}
Enter fullscreen mode Exit fullscreen mode

You can see it, right? What if we have more than three variables to assign?

Aliases to the rescue!

A destructured variable can have a different name than the property value. If that variable name does not exist, it will automatically be constructed and assigned with the value. If it exists, then JS will just assign the destructured value to the existed variable. In that way this can be used referring to any class's variable, like a normal variable.

class DevToClass {
  a1: string;
  a2: string;
  a3: string;

setVal(): void {
  ({a1: this.a1, a2: this.a2, a3: this.a3} = {a1: 'Hello!', a2: 'dev.to', a3: 'community'});
// this.a1: 'Hello!', this.a2: 'dev.to', this.a3: 'community'
}
}
Enter fullscreen mode Exit fullscreen mode

The redundant code for assignments is gone! Now all assignments will take place in one line.

I hope you found this article useful!

Check & Contact me on:

Top comments (0)