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

Obtain Page Parameters within a Nested Next.js Layout using App Router

My Next.js App Router has a nested dynamic page structure using catchall routes configured like this: app/stay/ |__[...category] | |__page.js |__[uid] | |__page.js |__layout.js Within the 'layout.js' file, there is a con ...

Ways to troubleshoot a serverless framework plugin issue

I have scoured the depths of the internet trying to find an answer to my question with no luck... I am eager to tackle a serverless plugin fix, but I'm struggling with how to attach the debugging process to the code. My development environment is vs ...

When using Next.js, having 13 parallel routes within a nested routing structure can trigger infinite rendering loops during

A strange phenomenon occurs where a page route inside a parallel route keeps re-rendering infinitely in development mode. app directory structure: app ├── page-with-parallel │ ├── @parallelroute │ │ └── page-inside-parallel ...

Unable to locate Babel plugin

I keep encountering an error with Babel saying Cannot find module 'babel-plugin-svg-sprite-loader' This is the content of my babel configuration file: { "presets": ["next/babel"], "plugins": [ ["sty ...

NextAuth version 4 has encountered an error with JWT_SESSION

I recently encountered this error: [next-auth][error][JWT_SESSION_ERROR] https://next-auth.js.org/errors#jwt_session_error Invalid Compact JWE { message: 'Invalid Compact JWE', stack: 'JWEInvalid: Invalid Compact JWE After upgrading ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

The name 'Queue' cannot be located in Typescript, error code ts(2304)

I'm currently trying to create a private variable of type InnerItem, but I keep encountering the following error: Error: Cannot find name 'Queue'.ts(2304) private savedItems: Queue<InnerItem> = new Queue<InnerItem>(20); Could ...

Changing the NextJS route triggers a re-render of the _app.js file due to the usage of next-i18next serverSide

export async function getServerSideProps({ locale }) { const data = await serverSideTranslations(locale, ['apple', 'home']); return { props: data, }; } export default function IndexPage() { return <h1>Hi!< ...

Creating a generic union type component in Typescript/Angular 10

My interfaces are as follows: export interface Channel { id: number; name: string; } export interface TvChannel extends Channel { subscribed: boolean; } export interface RadioChannel extends Channel { // marker interface to distinguish radio chan ...

Should NextJS frontend requests be directed to NextJS API before accessing the Rails API, or should they go directly to the Rails API?

I'm currently working on an application that combines a front-end built with NextJS and a back-end powered by Rails API. In NextJS, there is the option of utilizing the /api route to incorporate server-side code. I'm debating whether it's b ...

A declaration file for the 'vuelidate' module could not be located

When I was following the installation instructions for Vuelidate in Vuejs (), I encountered a warning message at this line: import Vuelidate from 'vuelidate' The warning states: There seems to be an issue with finding a declaration file for t ...

What is the best way to set up TypeScript to utilize multiple node_modules directories in conjunction with the Webpack DLL plugin?

Utilizing Webpack's DllPlugin and DllReferencePlugin, I create a distinct "vendor" bundle that houses all of my main dependencies which remain relatively static. The project directory is structured as follows: project App (code and components) ...

encountering difficulties calling setAttribute within a function

I am encountering an issue while attempting to use setAttribute() within toggleDiv(). My IDE does not seem to recognize the function and is throwing an error. How can I resolve this problem so that the function is recognized? This specific case relates t ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

What are the benefits of utilizing TypeScript declarations? How can you demonstrate their value with concrete examples?

I'm a bit confused about the use of declaration in TypeScript. It seems like the compiler doesn't compile it into the js file, so what is the purpose and advantage of using declaration? Can someone please explain this to me? ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

Angular 11 along with RxJS does not support the combineLatest method in the specified type

Hey there, I'm currently working on utilizing the combineLatest operator to merge two streams in Angular, but I keep encountering an error message stating that "combineLatest does not exist on type". I've attempted to move the code into a .pipe() ...

What is the process for updating the Vue template during runtime?

Currently, I am working on a CMS-based Vue page. Within this page, there is a root container that contains two child containers structured as follows: <div id="app"> <div class="above-the-fold">...</div> <di ...

What is the best way to create a flow or diagram similar to whimsical using React?

Looking to replicate this design in a React application, any suggestions on how I can achieve something similar? Here is the image for reference. ...

The useEffect hook may not function properly in a production build of NextJS

useEffect is behaving differently in development and production builds. Here is the code snippet: useEffect(() => { console.log("useeffect 1") return () => { console.log("useeffect 2") }; }, []) In development ...