corgrath
corgrath

Reputation: 12295

How to create an ErrorEvent in TypeScript?

According to this post

How to properly initialize en ErrorEvent in javascript?

You should be able to create an EventError with this code:

var error = new ErrorEvent('oh nose', {
    error : new Error('AAAHHHH'),
    message : 'A monkey is throwing bananas at me!',
    lineno : 402,
    filename : 'closet.html'
});

However, if you try this in the TypeScript playground:

https://www.typescriptlang.org/play/#src=var%20error%20%3D%20new%20ErrorEvent('oh%20nose'%2C%20%7B%0A%20%20%20%20error%20%3A%20new%20Error('AAAHHHH')%2C%0A%20%20%20%20message%20%3A%20'A%20monkey%20is%20throwing%20bananas%20at%20me!'%2C%0A%20%20%20%20lineno%20%3A%20402%2C%0A%20%20%20%20filename%20%3A%20'closet.html'%0A%7D)%3B

It says Supplied parameters do not match any signature of call target.

Even this simple example does not compile:

var error = new ErrorEvent('oh nose');

I have tried to figure it out by looking at the Type Definition

https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts#L9612

But can't figure it out.

What is missing to create a perfectly legal EventError in TypeScript?

Upvotes: 5

Views: 4619

Answers (2)

Nathan5x
Nathan5x

Reputation: 309

ErrorEvent is a type that extends from Event and uses ErrorEventInit inside. Here is the declaration https://github.com/microsoft/TSJS-lib-generator/blob/master/baselines/dom.generated.d.ts#L5410

Give this a try -

const errorInitEvent: ErrorEventInit = {
    error : new Error('AAAHHHH'),
    message : 'A monkey is throwing bananas at me!',
    lineno : 402,
    colno: 123,
    filename : 'closet.html'
};

const CustomErrorEvent = new ErrorEvent('MyErrEventType', errorInitEvent);

Upvotes: 1

David Sherret
David Sherret

Reputation: 106820

lib.es6.d.ts is not completely aligned with the spec.

You should log an issue on TypeScript's github, but for the time being you can edit lib.es6.d.ts to include the fix:

// add this interface
interface ErrorEventInit {
    // ...put the properties here...
}

// edit this declare var's new signature
declare var ErrorEvent: {
    new(type: string, eventInitDict?: ErrorEventInit): ErrorEvent;
    prototype: ErrorEvent;
}

Upvotes: 3

Related Questions