0

I have this code:

   let event = new Event('sumanload', {
      value: 'foo'
    });

    window.dispatchEvent(event);

Here is the error:

enter image description here

What I want to do is pass custom data as the event data. Is there a way to do this? Right now, TypeScript will complain if you include an unknown property.

6
  • what if you pass it to the instance? like event.value = 'foo'? Commented Feb 13, 2018 at 5:36
  • that might work, I will try it Commented Feb 13, 2018 at 5:38
  • it's a similar problem - I can't define a custom field on event itself, because the custom field/property does not exist...there must be some correct way to do this Commented Feb 13, 2018 at 5:40
  • Then I don't know. I see someone else encountered a similar issue on redux Commented Feb 13, 2018 at 5:44
  • 1
    Can you try a new CustomEvent object? They support a detail property of the initialization object with any data type. As per the link, some browsers need a polyfill (go on, guess which one). Commented Feb 13, 2018 at 6:09

1 Answer 1

0

You could try using a CustomEvent instead of an Event object. Custom event objects specifically allow you to add a detail property to the initialiser object passed as the second parameter during constructions.

let event = new CustomEvent('sumanload', {
    detail: 'foo'
});

window.dispatchEvent(event);

where detail can be of any data type including object.

I have successfully attached custom properties directly to a CustomEvent object in the past ( as in event.value = 'foo') but I don't know if TypeScript will let you do that.

Check the MDN link above for a polyfill if you need to support older browsers like IE.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.