What do square brackets mean where a field should be in typescript?

That is an index signature. From the TypeScript documentation:

Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

So, for example, you could define an interface for an indexable object like:

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

This tells the compiler, that for any object of type IArrayOfStrings, any member accessed by the numerical index will be of type string.

So, this will compile without error:

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

let words: IArrayOfStrings = ["foo","bar"];

let word: string = words[0];

But this will not:

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

let words: IArrayOfStrings = ["foo","bar"];

let myNumber: number = words[0];

In your example, this line:

dispatchEvent(event: { type: string; [attachment: string]: any; }): void;

is describing a method dispatchEvent that accepts one parameter of type { type: string; [attachment: string]: any; }.

To make that type easier to understand, look at an interface that defines this type:

interface IEvent {
    type: string;
    [attachment: string]: any;
}

This tells the compiler that objects of type IEvent will have a string property called type, and elements of an IEvent object, accessed by the string index will be of any type.

So, something like this would compile without error:

interface IEvent {
    type: string;
    [attachment: string]: any;
}

let myEvent: IEvent = {
    type: 'some-event-type'
};

let eventType: string = myEvent["type"];

Leave a Comment