在Typescript中解构分配

rad*_*ead 7 typescript angular

is代码可以通过解构对象并分配变量来正常工作,

const { allowNegative, decimal, precision, prefix, suffix, thousands } = this.options;
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用this下面的运算符时,它将引发错误:

`{ this.tabConfig, this.searchUiConfig, this.gridUiConfig } =  CONFIG;`
Run Code Online (Sandbox Code Playgroud)

其中CONFIG为JSON。错误是[ts]赋值运算符(=)上需要的声明或语句

有没有比这更好的方法:

 this.tabConfig = CONFIG.tabConfig;
 this.searchUiConfig = CONFIG.searchUiConfig;
 this.gridUiConfig = CONFIG.gridUiConfig;
Run Code Online (Sandbox Code Playgroud)

Bru*_*oLM 8

您可以使用以下语法进行操作:

({ prop: this.prop } = obj);
Run Code Online (Sandbox Code Playgroud)

在这里我正在使用深度对象匹配

var obj = { propIwantFromObj: 'foo' };
var { propIwantFromObj: whereToStoreValue } = obj;
Run Code Online (Sandbox Code Playgroud)

在左侧,您将说出您想从对象中获得哪个属性,在右侧,您将说出该值的存储位置。因此,在这种情况下,whereToStoreValue将创建一个带有foo值的新变量。

var obj = { propIwantFromObj: 'foo' };
var whereToStoreValue = obj.propIwantFromObj;
Run Code Online (Sandbox Code Playgroud)

可以将其用于存储this(或其他对象)上的值,但由于需要将其包装在括号中.。由于某种原因,此hack允许您使用.

如果不使用括号,则会出现语法错误(在纯JS中也不起作用)。

例:

({ prop: this.prop } = obj);
Run Code Online (Sandbox Code Playgroud)