Destructuring assignment in Typescript

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;

1 answer

  • answered 2018-01-11 20:48 BrunoLM

    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).


    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();;