How do you create custom Event in Typescript?

Issue

How do i create a customEvent Typescript and use it? I found this link on javascript on Mozilla site (https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent)

I am just doing some testing on custom Event but Typescript see it as an error. what i am planning on doing is add some extra data into the details property to use later: here is my code.

let div:any=document.getElementById("my_div");

let c_event = new CustomEvent("build",{'details':3 });

div.addEventListener("build",function(e:Event){
    console.log(e.details);
}.bind(this));

div.dispatchEvent(c_event);

Solution

The property name is detail and not details. The correct code needs to be:

let div: any = document.getElementById("my_div");

let c_event = new CustomEvent("build",{detail: 3});

div.addEventListener("build", function(e: CustomEvent) { // change here Event to CustomEvent
    console.log(e.detail);
}.bind(this));

div.dispatchEvent(c_event);

Answered By – Diullei

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.