Utilizing TypeScript with an express server and socket.io: 'App' type does not have property 'server'

Exploring a classic approach to setting up an expressjs server with socketio:

    this.app = express();
    this.server = http.createServer(this.app);
    this.io = socket(this.server);

Encountering errors when using TypeScript:

src/server/ts/app.ts(23,38): error TS2345: Argument of type 'Application' is not assignable to parameter of type '(request: IncomingMessage, response: ServerResponse) => void'.
src/server/ts/app.ts(24,8): error TS2339: Property 'io' does not exist on type 'App'.
src/server/ts/app.ts(24,25): error TS2339: Property 'server' does not exist on type 'App'.

In need of guidance on how to manage this situation. What would be the correct way to address these issues?

Answer №1

Here's a fix I came up with

In one of the controller functions:

(req.app as any).io as io.Server

Answer №2

It appears that your previous question was posted later than this one, so is this information still relevant?

Here's a technique I found successful: I organized my sockets into a separate config file because my app.js was becoming too cluttered.

app.use(express.static(path.join(__dirname, '/')));

app.use(express.static(path.join(__dirname, '/node_modules/')));

var clients = {};

var server = http.createServer(app);
var io = require('socket.io')(server);

require('./config/app.socket.js')(io);
server.listen(8001);
io.set("origins", "*:*");

By eliminating the intermediary step and passing the server directly to the socket.io import, I then pass the reference to the io server to my app.socket.js file to listen on port 8001.

Below is how I initialized my app.socket.js:

module.exports = function(io){
  var clients = {};

  var sockets;

  io.on('connection', function (socket) {
    sockets = socket;

    socket.on(//your socket function)

}

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

For every set of strings in an array, each one is added or updated and then increments by 1 while also storing a value of 2

Hello there, I have created an API using node.js, express.js, and MongoDB to store data. Within my routes, you can find: const { Tag } = require('../models/tag') router.patch('/', async (req, res) => { const { tags } = req.body ...

Observing changes in a parent component variable with Angular

One feature of my form is that it consists of a parent component and a child component. To disable a button within the form, I utilize a function called isDatasetFilesValid() which checks a specific variable (datasetList[i].fileValid). This variable is mo ...

Ensure the initial word (or potentially all words) of a statement is in uppercase in Angular 2+

Struggling with capitalizing words in an Angular 2 template (referred to as view) led to an error in the console and the application failing to load, displaying a blank page: Error: Uncaught (in promise): Error: Template parse errors: The pipe 'c ...

I have a range of products in my collection and I am looking to search and filter them based on their respective

async function retrieveTestProduct(req, res) { try { let searchQuery = req.query.search; const categoryQuery = req.query.category; const categoryFilter = categoryQuery ? categoryQuery : {}; const queryFilter = searchQuery ? { ...

Tips for extracting data from an Angular object using the *ngFor directive

https://i.stack.imgur.com/ai7g1.png The JSON structure displayed in the image above is what I am working with. My goal is to extract the value associated with the key name. This is the approach I have taken so far: <span *ngFor="let outlet of pr ...

Encountered a failure while attempting to execute npm install command for Express

Having trouble with the npm install express command due to an error? Here's the error message: $ npm install express npm ERR! fetch failed https://registry.npmjs.org/debug/-/debug-2.1.0.tgz npm ERR! fetch failed https://registry.npmjs.org/etag/-/etag ...

Display a pug template when a button is clicked using Node.js and Express framework

I am struggling to grasp the concept of forms, particularly when integrating them with Express. I want my application to display a new page upon clicking a button, but I find it challenging to comprehend express routes. Any assistance would be greatly appr ...

Exploring methods to broaden the functionality of components through inheritance

My goal is to develop extensions for existing Angular 2 components without having to completely rewrite them. I want any changes made to the base component to also automatically apply to its derived components. To illustrate my point, consider the followi ...

How to retrieve FormData data using Axios

One challenge I'm facing is with an application that I have developed using VueJS, where users can upload files and send them to the backend. The process involves using Axios to send the file as FormData. However, once the file is received on the back ...

In ES5, this.method does not exist as a function

I am facing an issue with a TypeScript 2 class that targets ES5. When I run it, I receive an error in the console stating that the increment() and decrement() methods do not execute, although the switch statement works fine. class MyClass extends React. ...

Deconstructing arrays in the req.body object in a Node.js Express application

Received an array in the request body as follows: [ { "month" : "JUL", "year" :"2018" }, { "month" : "JAN", "year" :"2018" }, { "month" : "MAR", "year" :"2018" } ] This array consists of two parameters (month:enum and year:string). ...

What steps can be taken to disable auto correction in ngx date picker?

In my application, I am utilizing ngx-datepicker with 'DD.MM.YYYY' as the dateInputFormat in the configuration settings of the date picker. The challenge arises when I manually input a date following the format 'YYYY.MM.DD', as the ente ...

Using Node.js, iterate over every key-value pair within a Redis hash data structure

I am currently navigating my way through the world of redis and node, attempting to iterate over some test hash keys that I have generated. My goal is to display the results on the screen. The expected output should look like this: { "aaData": [['Tim ...

What could be causing my webpack bundler to generate several main.js files?

After realizing that tree shaking was not working correctly due to compiling TypeScript to 'commonjs', I switched it to 'ES2015' and now my build output appears like this: click here for the image. Can anyone explain what is happening ...

When attempting to send a POST request to an Express route and receiving form data, the res.render function does not get activated

I'm currently working on developing a straightforward application where users can upload an image, which will then be displayed on an HTML canvas for pixel manipulation purposes. At the moment, I have set up the GET method to render an EJS template w ...

VSC is throwing a type error, but is it still possible to compile the code?

It seems like after downloading some extensions, I started encountering this issue which was not present before. My files are now displaying errors even though everything should be fine. https://i.sstatic.net/cr7Ef.png The error seems to be related to ca ...

Is it possible to assign an alternative name for the 'require' function in JavaScript?

To ensure our node module is executable and includes dependencies for requiring modules at runtime, we utilize the following syntax: const cust_namespace = <bin>_require('custom-namespace'); This allows our runtime environment to internal ...

Why aren't my arrays' characteristics being recognized when I create an instance of this class?

There is a puzzling issue with the arrays in my class. Despite creating them, when I try to access them in another class they are not recognized, only the otherProp is visible. To make matters worse, attempting to add elements to the arrays results in an ...

Global value stored in Sequelize queried store

I'm currently exploring ways to store an object that has been successfully queried using a global variable, so I don't have to run the same query on the model every time I need to access and use values from it. I keep encountering issues where I ...

Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message: Cannot read property 'populationService&a ...