You also need to use a string when assigning or retrieving a property with a name like this, as the normal dot syntax also can't be used for the same reason - it wouldn't be valid syntax for TypeScript code. To access a string property, square brackets [
and ]
are used instead of a dot, with the string in between.
let myObject = {
"my property!": 5
};
// Assign to a string property
myObject["my property!"] = 7;
// Read a string property
console.log(myObject["my property!"]); // 7
Providing the property has a valid name, you can access it both ways: with a dot or with a string.
let myObject = {
myProperty: 5
};
// Read with dot property
console.log(myObject.myProperty); // 5
// Read with string property
console.log(myObject["myProperty"]); // 5
This is essentially just an alternative syntax for accessing object properties. It allows more flexibility with property names, but we'd suggest using the standard syntax instead, as it is a bit more convenient to write.