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

The brackets declare an index signature, meaning beside type, which is mandatory, you can put anything into the first argument.

Basically this weakens the type safety of the argument. This mechanism is of great use if the function is not itself a consumer but a generic interlink between players using stronger typing (they'll have deeper knowledge of the event structure).

I added another answer because the existing answer named this an optional argument, which it is not. An optional argument is postfixed with a "?" and quite different.


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"];

Tags:

Typescript