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

前端 未结 3 776
清歌不尽
清歌不尽 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:40

    Now use can do things with ES6 new feature Map:

    let map: Map<string, EventEmitter<any>> = new Map<string, EventEmitter<any>>();
    
    0 讨论(0)
  • 2020-12-24 03:44

    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"];
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题