Reputation: 750
I have version 0.9.0.1 of the typescript compiler installed in my VS 2012 Update 3.
I want to dispatch a custom event but the ambient variable declared in lib.d.ts does not expose the expected constructor signatures.
When I use
var myEvent = new CustomEvent("my:event:type", { detail: { some: "data"} });
window.dispatchEvent(myEvent);
the type script compiler complains, because according to him, only
var myEvent = new CustomEvent();
is correct.
The latter is erroneous according to Chrome 27 and Aurora 24.02, due to "missing arguments"
MDN also lists the actually-correct-but-not-for-typescript constructor signatures.
My thinking was now to add the known-correct constructor signature to the ambient variable declaration, but without touching the shipped lib.d.ts file. Would this technically be possible? I could not come up with the correct syntax for it, and the language specification did not mention how to merge two such declarations.
Alternatively, I simply edited lib.d.ts, which after a restart of the IDE provided me with the updated signature. Nevertheless, I'd rather not tamper with 3rd-party files in such a way.
Last, is there some other mechanism I (sh|c)ould use to write type script code that dispatches a custom event?
(Update: Restarting the IDE reloads lib.d.ts correctly. Also, corrected made-up event type name)
Upvotes: 3
Views: 2765
Reputation: 1
var event = <CustomEvent>(new (<any>CustomEvent)('specifiedEvent'))
Might be a solution. Nice looking and tricky.
Upvotes: 0
Reputation: 251242
The reason this isn't part of lib.d.ts
is that Internet Explorer doesn't support this object in IE10.
If the CustomEvent
definition was purely an interface, you would be able to extend it thus:
interface CustomEvent {
new(eventType: string, data: {});
}
But the CustomEvent
constructor is actually defined in a variable declaration, which you can't extend:
declare var CustomEvent: {
prototype: CustomEvent;
new(): CustomEvent;
}
You can use this (nasty looking) work around to get hold of custom events while you wait for Internet Explorer / the TypeScript library to be updated.
class StandardsCustomEvent {
static get(eventType: string, data: {}) {
var customEvent = <any>CustomEvent;
var event = new customEvent(eventType, data);
return <CustomEvent> event;
}
}
var x = StandardsCustomEvent.get("myevent", { detail: { some: "data"} });
This fixes your compiler warnings - but won't make it work in IE10 or older - you would need to polyfill.
Upvotes: 3