0

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?

Tomasz Waszczyk
  • 2,680
  • 5
  • 35
  • 73
  • can you add respective code to understand. – Avinash Dalvi Jul 09 '20 at 11:19
  • `{ modifier: 1 }` is just a normal object as you would expect. `{ [foo]: bar }` is just creating a new object where `foo` a variable string (unlike `modifier`). An alternative for the former is `{ ['modifier']: 1 }` -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors – Caramiriel Jul 09 '20 at 11:19
  • Related: https://stackoverflow.com/questions/32515598/square-brackets-javascript-object-key – Caramiriel Jul 09 '20 at 11:22
  • So how to make minimum viable working code in: https://repl.it/@tomaszwaszczyk/in-TypeScript ? – Tomasz Waszczyk Jul 09 '20 at 11:30

1 Answers1

3

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 } }
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53