Foreign
Foreign

Reputation: 405

Can TypeScript identify custom types over events?

import express from "express";
import io_server from "socket.io";
import io_client from "socket.io-client";

type Message = {
    from: string
    to: string
};

(function server() {

    const http = express();
    const wss = io_server(http.listen(9999));

    wss.on("connection", socket => {

        socket.on("test", (message: Message) => { // "test" expects type 'Message'
            console.log("Message:", message);
        });
    });

})();

(function client() {

    const wss = io_client("http://localhost:9999");

    setTimeout(() => {
        wss.emit("test", { anything: "wrong type" }); // WRONG TYPE IS BEING SENT HERE.
    }, 1000);

})();

Currently I can make a mistake and send the wrong object over the "test" event. As you can see, my socket.on("test") expects that a 'Message' type object will be received.

Is it possible to make TypeScript to identify if I'm sending the correct type over events?

I know that types are removed when TS is compiled. I'm interested in this to prevent errors during development .

Upvotes: 0

Views: 698

Answers (1)

Dor Shinar
Dor Shinar

Reputation: 1512

Yes, and no. Looking at @types/socket.io we can see the type of the emit function declared as:

declare namespace SocketIO {
    interface Server {
        /* Other functions */

        /**
         * Emits an event to the default Namespace
         * @param event The event that we want to emit
         * @param args Any number of optional arguments to pass with the event. If the
         * last argument is a function, it will be called as an ack. The ack should
         * take whatever data was sent with the packet
         * @return The default '/' Namespace
         */
        emit( event: string, ...args: any[]): Namespace;
    }
}

So, as far a the typescript compiler is concerned, you can pass any argument to the emit function and it would be acceptable. You can, however, re-declare the namespace and alter the type declaration. You can find the documentation here, and you can use this question for further help.

Upvotes: 1

Related Questions