Enhanced Object Literals
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:
const zipCode = '07030';
const street = 'River';
const houseNumber = '234';
// old syntax
const address = {
zipCode: zipCode,
street: street,
houseNumber: houseNumber,
};
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:
// ES2015 syntax
const address = {
zipCode,
street,
houseNumber,
};
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:
const calculator = {
add: function(num1, num2) {
return num1 + num2;
},
multiply: function(num1, num2) {
return num1 * num2;
},
};
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