1

I am trying to construct and dispatch a MouseEvent in TypeScript. The simulateClick() example from mozilla.org gives a compile error calling the constructor:

"Supplied parameters do not match any signature of call target."

function simulateClick() {
    var event = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true
    });
    var cb = document.getElementById('checkbox');
    var canceled = !cb.dispatchEvent(event);
    if (canceled) {
        // A handler called preventDefault.
        alert("canceled");
    } else {
        // None of the handlers called preventDefault.
        alert("not canceled");
    }
}

I have tried inserting a cast <MouseEventInit> before the parameter dictionary, but that results in the same error.

Even the following results in the same error:

new MouseEvent('click', <MouseEventInit>null);

Although it looks like it matches the prototype in lib.d.ts:

new(typeArg: string, eventInitDict?: MouseEventInit): MouseEvent;

Workaround:

var event: MouseEvent = new (<any>MouseEvent)('click',
    { 'view': window, 'bubbles': true, 'cancelable': true });
Jason Kresowaty
  • 16,105
  • 9
  • 57
  • 84

2 Answers2

4

The earliest TypeScript version that seems to compile this successfully is 1.5. The following works around the problem in 1.4:

var event: MouseEvent = new (<any>MouseEvent)('click',
    { 'view': window, 'bubbles': true, 'cancelable': true });
Jason Kresowaty
  • 16,105
  • 9
  • 57
  • 84
1

Your code snippet is correct. I tried it in the playground, even on my own computer (both TypeScript 1.6).

I would suggest to try to compile it as a standalone code snippet first on your computer.

MartyIX
  • 27,828
  • 29
  • 136
  • 207