BnMcG
BnMcG

Reputation: 688

TypeScript, type definitions, and websockets/ws: How to access event information?

I think this is more of a general TypeScript definitions question, but the context I'm using it is with the websockets/ws package.

I have some code defined like so:

import { LoggerInstance } from "winston";
import "ws";

export abstract class MyClass {
    private _logger: LoggerInstance;
    private _webSocket: WebSocket;

    constructor(logger: LoggerInstance webSocket: WebSocket) {
        this._logger = logger;

        this._webSocket = webSocket;
        this.configureWebSocket();
    }

    private configureWebSocket(): void {
        this._webSocket.addEventListener("open", (event: Event) => {
            this._logger.info("WebSocket connection opened");
        });

        this._webSocket.addEventListener("message", (event: MessageEvent) => {
            this._logger.debug("WebSocket message received");
        });

        this._webSocket.addEventListener("error", (event) => {
            this._logger.error("WebSocket error encountered");
        });

        this._webSocket.addEventListener("close", (event: CloseEvent) => {
            this._logger.info("WebSocket connection closed");
        });

    }
}

But I'd like to be able to get the error message itself out - looking at the @types/ws definition, I can see there's a definition like so:

addEventListener(method: 'error', cb?: (event: {error: any, message: any, type: string, target: WebSocket }) => void): void;

However, I'm not sure how to format my code in such a way that properties like "type" and "message" are available.

I've tried passing them as parameters into my anonymous function, like so:

this._webSocket.addEventListener("error", (event, message) => {

but then TypeScript complains that the function signature doesn't match its expected signature.

If somebody could explain how I can do this, or point me towards some relevant documentation, I'd be grateful.

Thanks.

Upvotes: 4

Views: 12031

Answers (1)

BnMcG
BnMcG

Reputation: 688

I looked at the tests for the type definitions after posting this question (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/ws/ws-tests.ts)

It seems like the correct way to import ws is as so: import WebSocket = require("ws");. Once I do this, I then have the option of either using:

this._webSocket.on("error", (error: Error) => { ... });

or:

this._webSocket.addEventListener("error", (error) => { error.message... });

VS Code also started correctly hinting the properties on the plain error object for me once I changed my import syntax.

I'm going to look into when to use different import syntax in TypeScript, as it's clear I don't quite understand it in its entirety yet.

Thanks.

Upvotes: 4

Related Questions