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 ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.