3

I saw this TypeScript code somewhere. It compiles without any issues:

const eventName = entityName + commandName;
pubsub.publish(triggerName, { [eventName]: response });

I assumes it dynamically creates an object literal with property name called eventName. Is this assumption correct? Where in the TypeScript docs is this feature described?

Naresh
  • 18,757
  • 25
  • 99
  • 162

1 Answers1

6

That is not a typescript feature but a javascript one. It's called a computed property. Here are the docs for it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names

Additionally, it does not create a property with the key eventName, but instead creates a property with a key that is the value of the variable eventName. Eg, if eventName = "foo", then {[eventName]: "bar"} is the same as {foo: "bar"}.

CRice
  • 22,449
  • 3
  • 48
  • 54
  • 1
    Direct link to "Computed property names" section on page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names – Mike Hill Nov 28 '17 at 21:55
  • 1
    @MikeHill thanks, I've edited my answer to include your link. – CRice Nov 28 '17 at 21:57