6

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
  • 23,937
  • 33
  • 132
  • 204

1 Answers1

10

That is not a typescript feature but a javascript one. It's called a computed property. Here are the docs for it.

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
  • 29,968
  • 4
  • 57
  • 70
  • 2
    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
  • 2
    @MikeHill thanks, I've edited my answer to include your link. – CRice Nov 28 '17 at 21:57