Enhanced Object Literals#

ES2015 enhanced the syntax for creating object literals by introducing three changes that facilitate common patterns:

  • Shorthand property names

  • Sorthand method names

  • Computed property names

We'll give an overview of the three cases and discuss the TypeScript implications of these enhancements.

Shorthand for property names#

When creating object literals, the name of the keys often matches the names of variables in the outer scope. In the example below, we create an object address that contains properties describing an address:

Because the property names of address match the variable names in the outer scope, we can use the ES2015 syntax to create the object without rewriting the variable names:

Shorthand for method names#

When adding a method to an object literal, we have two options: define the function in the outer scope and add it as a property of the object or define the function inline using an anonymous function. Below we demonstrate the latter:

The shorthand for method names helps with this notation, letting us declare a function while assigning a name to the property in one go:

 

This page is a preview of Beginners Guide to TypeScript

Start a new discussion. All notification go to the author.