String or Number Indexes
This lesson discusses the two ways to access an index.
The index signature can define members of an object with an identifier with square brackets.
myObject["memberName"] = "Value Here";
The identifier type can only be a string
or a number
. The identifier is the name between the brackets. In the previous example, it was memberName
. In the following example, we can see an identifier with a string and another with a number;
myObject["String Here"] = {name:"anything"}; // string identifier
myObject[100] = true; // number identifier
Index signatures can be useful if you want to control the type of key for a dynamic assignment as well as the type to be returned.
For example, imagine having a custom map type that allows you to have a string key and return a specific type of object. Having a defined index signature allows for a strongly-typed key (string or number) that can hold an explicit type. In the following example, line 2 defines the type of index signature. The identifier must be a number
while the value, a string
. Line 4 demonstrates how to create a new object with two values with identifier 100
and 200
.
Get hands-on with 1400+ tech skills courses.