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

前端 未结 3 789
清歌不尽
清歌不尽 2020-12-24 03:27

I came across this line in three.d.ts:

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

and was wondering what it

3条回答
  •  余生分开走
    2020-12-24 03:57

    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.

提交回复
热议问题