Learning TypeScript 2.x
上QQ阅读APP看书,第一时间看更新

Index signature

In JavaScript, we can access the properties of an object using the name of the object followed by a dot and the name of the property:

let foo: any = {};
foo.hello = 'World';
console.log(foo.hello); // World

However, it is also possible to access the properties of an object using the name of the object followed by the name of the property as a string wrapped by brackets:

let foo: any = {};
foo['hello'] = 'World';
console.log(foo['hello']); // World

This behavior can be declared using what is known as the index signature:

interface StringArray {
[index: number]: string;
}

let myArray: StringArray = ["Bob", "Fred"];
let myStr: string = myArray[0];

As we can see in the preceding code snippet, the index signature allows us to specify the type of the value returned when we access a property using the brackets signature.