Typescript中的销毁分配 [英] Destructuring assignment in Typescript

查看:274
本文介绍了Typescript中的销毁分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

is代码可以通过分解对象并分配变量来很好地发挥作用,

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

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

但是当我尝试使用如下所示的this运算符时,会引发错误:

But when i try with this operator like below it throws an error:

`{ this.tabConfig, this.searchUiConfig, this.gridUiConfig } =  CONFIG;`

其中 CONFIG 是JSON.在赋值运算符(=)上出现 [ts]声明或声明 时出错.

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;

推荐答案

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

You can do it with the following syntax:

({ prop: this.prop } = obj);

这里我使用的是深度对象匹配

var obj = { propIwantFromObj: 'foo' };
var { propIwantFromObj: whereToStoreValue } = obj;

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

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;

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

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

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

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();
foo.bar();

console.log(foo.tabConfig);
console.log(foo.searchUiConfig);
console.log(foo.gridUiConfig);

这篇关于Typescript中的销毁分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆