简体   繁体   English

[]: TypeScript 中的 {} 语法

[英][] : {} syntax in TypeScript

I have following source code:我有以下源代码:

const positions = {
  [modules.module1.tasks.t1.id]: { modifier: 1 },
};

Anybody can explain or link to documentation what is done above?任何人都可以解释或链接到文档上面做了什么?

There is nothing specific to TypeScript in your code sample.您的代码示例中没有特定于 TypeScript 的内容。 It's just modern JavaScript.它只是现代 JavaScript。

Let's decompose what is happening here:让我们分解这里发生的事情:

[modules.module1.tasks.t1.id]

This is a computed property name .这是一个计算的属性名称 It means the position object will have a property equal to modules.module1.tasks.t1.id .这意味着position object 将具有等于modules.module1.tasks.t1.id的属性。

If modules.module1.tasks.t1.id is a string, then this property will be exactly the same.如果modules.module1.tasks.t1.id是一个字符串,那么这个属性将完全相同。 Otherwise, modules.module1.tasks.t1.id will be coerced into a string.否则, modules.module1.tasks.t1.id将被强制转换为字符串。

{ modifier: 1 }

Our dynamic property will have a value of { modifier: 1 } .我们的动态属性的值为{ modifier: 1 } It's just a regular property assignment.这只是一个常规的财产分配。

Example例子

const modules = {
  module1: {
    tasks: {
      t1: {
        id: 'foo'
      }
    }
  }
}

const positions = {
  [modules.module1.tasks.t1.id]: { modifier: 1 },
}; // evaluates to { foo: { modifier: 1 } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM