Tomasz Waszczyk
Tomasz Waszczyk

Reputation: 3159

[] : {} 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?

Upvotes: 0

Views: 59

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25800

There is nothing specific to TypeScript in your code sample. It's just modern 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.

If modules.module1.tasks.t1.id is a string, then this property will be exactly the same. Otherwise, modules.module1.tasks.t1.id will be coerced into a string.

{ modifier: 1 }

Our dynamic property will have a value of { 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 } }

Upvotes: 3

Related Questions