Issue
I came across this line in three.d.ts:
dispatchEvent(event: { type: string; [attachment: string]: any; }): void;
and was wondering what it meant.
I understand that this would mean a function called dispatchEvent which takes an argument of a type with a member type but I am not sure what:
[attachment: string]: any;
means.
Solution
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"];
Answered By - Seamus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.