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.
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] .
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.
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 .
Use Object.assign
from within your class:
Object.assign(this, paginationConfig);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With