4
\$\begingroup\$

I could not find any definitions of the EventSource object that belongs to Server-Sent Events, so I create the definitions. That's how they look like:

declare var EventSource : sse.IEventSourceStatic;

declare module sse {

    enum ReadyState {CONNECTING = 0, OPEN = 1, CLOSED = 2}

    interface IEventSourceStatic extends EventTarget {
        new (url: string, eventSourceInitDict?: IEventSourceInit);
        url: string;
        withCredentials: boolean;
        CONNECTING: ReadyState; // constant, always 0
        OPEN: ReadyState; // constant, always 1
        CLOSED: ReadyState; // constant, always 2
        readyState: ReadyState;
        onopen: Function;
        onmessage: (event: IOnMessageEvent) => void;
        onerror: Function;
        close: () => void;
    }

    interface IEventSourceInit {
        withCredentials?: boolean;
    }

    interface IOnMessageEvent {
        data: string;
    }
}

Also available on GitHub.

I am new to TypeScript so I wonder if this definition is OK with common best practices and whether it could be improved.

\$\endgroup\$
  • \$\begingroup\$ Does this definition mean that you're attaching to the events like eventSource.on('onmessage', ...) ? (note: I'm also a beginner in TS) \$\endgroup\$ – MayaLekova Sep 19 '16 at 11:44
  • \$\begingroup\$ Just want to say I'm using your definition in a project and it's working fine and helping my concentrate on more productive things. Thanks :-) \$\endgroup\$ – Forbesmyester Nov 14 '16 at 10:31
1
\$\begingroup\$

According to your definition file, I'm assuming there's a global class called EventSource

If that's the case, I have the following improvements:

  • Avoid Function (or Object or Array), describe the signature accurately (like you did with onmessage). If you don't know the return type or the argument, apply any liberally. At least you're explicit about not knowing.
  • TypeScript has literal string, number and enum types, so you could do something like CONNECTING: ReadyState.CONNECTING

All in all, it's a fine definition file.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.