Learn TypeScript in Construct, part 8: Objects

UpvoteUpvote 3 DownvoteDownvote

Index

Features on these Courses

Stats

134 visits, 157 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Published on 11 Jul, 2025.

String properties

Object properties can also use a string for their name. This is not possible with variables, so is a special capability for properties. Here's an example using a string for a property name.

let myObject = {
	// Use a string for a property name
	"myProperty": 5
};

// This is equivalent to:
let myObject = {
	myProperty: 5
};

Normally property names have similar naming rules to variables: no spaces, no special characters, and so on. However using a string lets you use any name. For example you cannot use a space or exclamation mark in a property name unless you use a string for the property name.

// String properties allow spaces and special characters
let myObject = {
	"my property!": 5
};

// Normal properties don't allow this
let myObject = {
	// Syntax error
	my property!: 5
};

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.

  • 0 Comments

Want to leave a comment? Login or Register an account!