Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring assignment in Typescript for global variables

I have the following statement:

I'm receiving an object from somewhere like the following in example:

paginationConfig = {
  currentPage: 1,
  pageSizes: [5, 10, 15],
  perPage: 20
};

My class:

export class MyComponent implements OnInit {

  currentPage: number;
  pageSizes: number[];
  perPage: number;

  constructor() { }

  ngOnInit(): void {
    { this.currentPage, this.perPage, this.pageSizes } = paginationConfig; 
    // It prints undefined for all those variables and I receive the error:
    // TS1128: Declaration or statement expected.

    // It works for local variables (as below), why not when I use **this**?
    const { currentPage, pageSizes, perPage } = paginationConfig;
  }
}

So what I'm trying to do is destructure the object like the examples in this book.

I can get it work if I use local variables, but in my case I really want these as global. Isn't it possible/supported?

PS: I already tried to wrap everything in parenthesis, it doesn't work either.

like image 376
dev_054 Avatar asked Feb 15 '17 02:02

dev_054


People also ask

How do you swap variables using Destructuring assignment?

Destructuring assignment[a, b] = [b, a] is the destructuring assignment that swaps the variables a and b . At the first step, on the right side of the destructuring, a temporary array [b, a] (which evaluates to [2, 1] ) is created. Then the destructuring of the temporary array occurs: [a, b] = [2, 1] .

What is Destructuring in TypeScript?

Tuples in TypeScript are basically a simple Array with definite length and definite Data-type. Destructuring means breaking the structure. In this article we will see how Destructuring of tuple in TypeScript work. Destructuring is simply breaking up into part and assigning to variables.

How do I create a global variable in TypeScript?

To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods. TypeScript looks for .


1 Answers

Use Object.assign from within your class:

Object.assign(this, paginationConfig);
like image 58
pixelbits Avatar answered Sep 19 '22 11:09

pixelbits