The is code works fine by destructuring the object and assigning the variables,
const { allowNegative, decimal, precision, prefix, suffix, thousands } = this.options;
But when i try with this
operator like below it throws an error:
{ this.tabConfig, this.searchUiConfig, this.gridUiConfig } = CONFIG;
where CONFIG being a JSON. Error being [ts] Declaration or statement expected on the assignment operator(=).
Is there a better way of doing than this:
this.tabConfig = CONFIG.tabConfig;
this.searchUiConfig = CONFIG.searchUiConfig;
this.gridUiConfig = CONFIG.gridUiConfig;
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.
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.
Destructuring in Objects When destructuring objects, we use curly braces with the exact name of what we have in the object. Unlike in arrays where we can use any variable name to unpack the element, objects allow just the use of the name of the stored data.
Default values in destructuring assignement only work if the variables either don't exist or their value is set to undefined . Any other value, including null , false and 0 , bypasses the default values in the destructuring statement. You can combine default values with renaming in the destructuring assignment.
You can do it with the following syntax:
({ prop: this.prop } = obj);
Here I'm using a deep object matching
var obj = { propIwantFromObj: 'foo' };
var { propIwantFromObj: whereToStoreValue } = obj;
On the left part you will say which property you want to get from the object and on the right side you are going to say where to store the value. So in this case a new variable called whereToStoreValue
will be created with foo
value.
var obj = { propIwantFromObj: 'foo' };
var whereToStoreValue = obj.propIwantFromObj;
That can be used to store values on this
(or other object), but you need to wrap it around parenthesis because of the .
. For some reason this hack allows you to use .
.
If you don't use the parenthesis you will get syntax errors (it won't work in pure JS either).
Example:
const CONFIG = {
tabConfig: 1,
searchUiConfig: 2,
gridUiConfig: 3,
};
class Foo {
bar() {
({ tabConfig: this.tabConfig, searchUiConfig: this.searchUiConfig, gridUiConfig: this.gridUiConfig } = CONFIG);
}
}
const foo = new Foo();
foo.bar();
console.log(foo.tabConfig);
console.log(foo.searchUiConfig);
console.log(foo.gridUiConfig);
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