Destructuring assignment in Typescript

后端 未结 1 453
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 20:36

The is code works fine by destructuring the object and assigning the variables,

const { allowNegative, decimal, precision, prefix, suffix, thousands } = this         


        
相关标签:
1条回答
  • 2021-01-11 21:15

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

    0 讨论(0)
提交回复
热议问题