What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript.

import { Server } from "Socket.IO";

const SocketHandler = (req, res) => {
  if (res.socket.server.io) {
    console.log("Socket is already running");
  } else {
    console.log("Socket is initializing");
    const io = new Server(res.socket.server);
    res.socket.server.io = io;

    io.on("connection", (socket) => {
      socket.on("update-messages", (msg) => {
        socket.broadcast.emit("update-messages", msg);
      });
      socket.on("user-typing", (msg) => {
        socket.broadcast.emit("user-typing", msg);
      });
    });
  }
  res.end();
};

export default SocketHandler;

I attempted translating it into TypeScript by using "any" as the type for the response object, but I'm not satisfied with this approach.

Answer №1

After receiving assistance from @Anatoly, I successfully converted it to Typescript:

import { Server } from "socket.io";
import { Request, Response } from "express";

const SocketHandler = (req: Request, res: Response): void => {
  if (res.socket.server.io) {
    console.log("Socket is already running");
  } else {
    console.log("Socket is initializing");
    const io: Server = new Server(res.socket.server);
    res.socket.server.io = io;

    io.on("connection", (socket) => {
      socket.on("update-messages", (msg) => {
        socket.broadcast.emit("update-messages", msg);
      });
      socket.on("user-typing", (msg) => {
        socket.broadcast.emit("user-typing", msg);
      });
    });
  }
  res.end();
};

export default SocketHandler;

It was necessary to import the Request and Response types from express.

If you need more information, check out this resource:

I hope this explanation clarified everything for you! Best regards, Alvin Cheng

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble accessing the admin-ui panel through socket.io? It seems like there may be an issue with

My code is based on a tutorial I found, but I'm experiencing an error when trying to connect: const express = require('express'); const http = require('http'); const { Server } = require('socket.io'); const { instrument } ...

Establish a reactive form upon data completion (asynchronously) in Angular version 5

I've been encountering an issue with updating form values post fetching data from an API. I attempted to utilize the *ngIf technique, but unfortunately, the form remains invisible even though it is properly set. Although I cannot provide the entire p ...

What causes the useEffect hook to render twice in a Next.js application?

Within my Next.js application, I am seeking a way to verify whether a user has permission to access a particular page. While using a context, I encountered an issue where my useEffect hook was returning both the updated and default values. How can I ensure ...

Having trouble verifying exceptions in TypeScript/Node.js using Chai

I am facing an issue while trying to test a simple function using chai assertion in my TypeScript code. Here is the function I have: public async test1(){ throw (new Error(COUCH_CONNECTION_ERROR.message)); } The definition of COUCH_CONNECTION_ERROR ...

Using Next.JS useRouter to access a dynamic route will result in receiving an empty object as the return value

I've encountered an issue with dynamic routing in my specialized calendar application built with Next.JS. One of my pages is working perfectly fine while the other is not functioning at all. The first page (working): // pages/date/[year]/[month]/[day ...

How can I specify the type of an object in Typescript to mirror a class's properties as a list?

This demonstration is kept simplistic and straightforward, yet the ultimate objective is far more intricate. It is crucial to grasp the method behind achieving this. Let's assume there exists a class class Foo { bar: string; baz: number; bob: a ...

Guide to Integrating Pendo with Angular 8 and Above

I'm having some trouble setting up Pendo in my Angular 8 application. The documentation provided by Pendo doesn't seem to align with the actual scripts given in my control panel. Additionally, the YouTube tutorials are quite outdated, appearing t ...

Checking a sequence using a list of strings

I have an array containing a list of IDs: var listId: string[] = []; var newId: boolean; for (let i in data.chunk) { listId.push(data.chunk[i].aliases[0]); } My objective is to compare a new ID with the entire list. If the new ID is found in the list ...

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

What are the best strategies to troubleshoot issues during NPM Install?

I keep encountering errors during the npm install process, but everything works fine when I use npm install --force in my local environment. However, the issues persist during the repository build as my .yaml file script contains "npm install". Can anyone ...

Is there a way for me to navigate from one child view to another by clicking on [routerLink]?

Currently, I am facing an issue with switching views on my Angular website. The problem arises when I attempt to navigate from one child view to another within the application. Clicking on a button with the routerlink successfully takes me to the new view, ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...

Mapping objects in Typescript to create a union of objects

I have been working on some TypeScript code and I seem to be having trouble getting it to work as expected. It would be greatly appreciated if someone could help me understand what I'm doing wrong or suggest a different approach. Let's assume I ...

Incorrect deduction of the argument type for a higher-order function

If I wanted to create a function that takes an object of type T and another value, where the type P should somehow be restricted by T (for example, P should be an array of keys of T), I could easily write it like this: function customFunction<T, P exte ...

Angular service is able to return an Observable after using the .then method

I am currently facing an issue with retrieving the authentication status in a service method. Everything seems to be working fine except for the return statement. I am struggling with the usage of .then inside .map and I am unable to figure out how to retu ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

Issue TS2315: Type 'ElementRef' does not support generics

While attempting to integrate @angular/materials into my application, I encountered a successful compilation with the following error messages: webpack: Compiled successfully. ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.t ...

Challenges with character encoding in NextJS

I am currently dealing with a line of code that creates a dynamic route. <Link href={`/bundeslander/${urlName}`} ><div className=" text-blue-400">{state.name}</div></Link> The variable urlName is generated by fetching dat ...

Tips for accessing a cookie that was set in the server.js file on Next.js 14 within an API route

In the server.js file of my Next 14 application, I have the following code: // Middleware to extract tenant from subdomain server.use((req, res, next) => { const hostname = req.hostname; const subdomain = hostname.split('.&a ...

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...