I'm using TypeScript 4.4.4 and I'm trying to use this EventSource polyfill in my frontend (React): https://github.com/EventSource/eventsource. I've also installed the type definitions for that package.
I specifically need to add headers to the SSE initiation: eventSourceRef.current = new EventSource('/api/foo', { headers: { bar: 'buzz' } });
. Unfortunately, the type definitions aren't being picked up. TypeScript complains if I try to add headers
as a property to the EventSourceInit
options, which means that the types of the baked in EventSource
are still being used, not the polyfill definitions.
I suspect it might have something to do with that the polyfill package doesn't export the class itself, so I can't import the class. I have to import the whole package, like this: import 'eventsource/lib/eventsource-polyfill';
I've tried the following:
- import the polyfill in my entry file
- import the polyfill only in the file that I need it
- import the type definition reference:
/// <reference path='../../../../../node_modules/@types/eventsource/index.d.ts'/>
- extend the global type and try to extend the
EventSourceInit
interface with the new properties allowed by the polyfill, like so:
export {};
declare global {
interface EventSourceInit {
headers?: object | undefined;
}
}
I realize I could always just cast it as any or import using require, but I feel like if there are type definitions for this it should be possible to use them in my project.
What am I missing here?
Edit: I also tried the following, but none worked either:
- import the package as shown in the type definition tests:
import EventSourcePolyfill = require("eventsource/lib/eventsource-polyfill");
. This doesn't work because I'm targeting ECMAScript modules. - import it like this:
import EventSourcePolyfill from "eventsource/lib/eventsource-polyfill";
. However, when calling the constructor (const foo = new EventSourcePolyfill('/foo)
) TypeScript complains that the expression is not constructable, as "Type 'typeof EventSource' has no construct signatures".
Sigh... I found the way. I started typing out the
EventEmitter
class in an expression and I noticed the intellisense suggesting the class coming from the package. This is the way to import it, apparently:import EventSource from 'eventsource';
I had been trying to import 'eventsource/lib/eventsource-polyfill' as per the instructions in the package README:
I got confused by that and tried importing the wrong thing. But apparently just importing the package index suffices. I guess the simplest answer really is the best.