I'm trying to use an EventSource
with Typescript but cannot type correctly the response when using named events.
I tried
const evtSource = new EventSource('/my-url');
const parseMyEvent = (evt: Event) => {
const data: MyDataInterface = JSON.parse(evt.data);
console.log(data)
}
evtSource.addEventListener('my-event', parseMyEvent);
Fails, because Event
has no property data
const evtSource = new EventSource('/my-url');
const parseMyEvent = (evt: MessageEvent) => {
const data: MyDataInterface = JSON.parse(evt.data);
console.log(data)
}
evtSource.addEventListener('my-event', parseMyEvent);
Fails on evtSource.addEventListener('my-event', parseMyEvent)
, with "No overload matches this call.
".
I know that MessageEvent
is a generic interface, but what should I use as its type?
I'm using TS 3.5.3 so I tried to install the external type @types/eventsource
with no luck too (I know, it is for the polyfill EventSource lib, but I tried)
When using the generic evtSource.onMessage = fn
it works without any problems
It should be possible to type the listener/response of a EventSource event in TS, but how?
EventSource.addEventListener
addEventListener<K extends keyof EventSourceEventMap>(type: K, ....
but it but it only accepts"error" | "message" | "open"
so that's not helpful. – Tightlipped