Transforming the express app object into a data type instead of a regular variable

Currently, I am setting up my own TypeScript Express project and aiming to abstract the code for better organization. In my app.ts file, the code looks like this:

import express from 'express'


const app = express();
const port = 3000;
require('./routes')(app)


app.listen(port, err => {
    if (err) {
        return console.error(err);
    }
    return console.log(`server is listening on ${port}`);
});

export default app

I am trying to segregate all routes configured in this app into a separate folder for easier navigation.

In my routes.ts file, the code is as follows:

const testController = require('./controllers/test')
import app from './app';


module.exports = (app) => {
    app.get('/test',
        testController.testingRoute)
}

The issue arises when attempting to run the script or analyze the code, it displays an error stating

Parameter 'app' implicitly has an 'any' type
. If I try to specify app:app, another error pops up saying
'app' refers to a value, but is being used as a type here.

I want to refrain from disabling type checking in tsconfig, as I believe TypeScript's type system is integral to its functionality. How should I go about tackling this problem?

Answer №1

If you're looking to streamline your routing in Express, consider using the express.Router class designed for exactly that purpose:

// customRouter.js
import express from "express"
const customController = require('./controllers/custom')

const customRouter = express.router()

customRouter.get("/custom-route", customController)

export default customRouter
// app.js
import express from 'express'
import customRouter from './customRouter'

const app = express();
const port = 3000;
app.use("/", customRouter)

app.listen(port, err => {
    if (err) {
        return console.error(err);
    }
    return console.log(`Server is now running on port ${port}`);
});

export default app

For more details and advanced functionality, refer to http://expressjs.com/en/5x/api.html#router

Answer №2

Commenting on the original question, @slebetman offered a potential solution:

const sampleController = require('./controllers/sample')
// import app from './app';
import { Application } from 'express';

module.exports = (app: Application) => {
    app.get('/sample',
        sampleController.sampleRoute)

}

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

Sending the req.session data to a different route

Currently working on implementing a login session in nodejs, In my app.js file: app.post('/login', async(req, res) => { const { login, password } = req.body const admin = await register.findOne({ where: { login } }) if (await bcrypt.compare( ...

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

Encountering difficulties in constructing next.js version 14.1.0

When attempting to build my next.js application, I use the command npm run build Upon running this command, I encountered several errorshttps://i.sstatic.net/5jezCKHO.png Do I need to address each warning individually or is there a way to bypass them? B ...

In search of a render function that can effectively apply styles to HTML strings using React JS

I have been struggling to convert the result field value, including HTML attributes string, into respective styles for one column in my antd table. Below is the string I am trying to convert: The exhaust air requirements for fume hoods will be based on m ...

Ways to ensure a function is only triggered once using onmouseover

I'm fairly new to JavaScript and I've been attempting to create a function that only runs once. Here's the logo I've been trying to animate: <img src="img/logot2.png" id="logoutjs" onmouseover="move()" ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Initial request fails to retrieve cookie generated by Javascript

I created a shopping cart that generates a cart, adds items, and stores it in a cookie named 'cart'. However, when I click on a hyperlink that leads to the checkout page, my ASP.NET application is unable to access the cookie. The cookie only get ...

A method of submitting by simply pressing the enter key alongside clicking on a Bootstrap button

Here is the HTML code I am using to input prompts into a chatbot: <div class="input-group mb-3"> <input type="text" class="form-control" id="chat-input"> <div class="input-group-append ...

JavaScript Code: Empty a text box when a different one is active

Looking for a solution to clear the content of one textbox when the user interacts with another in HTML and JavaScript. <input id="tb1" type="text" name="textbox1"> <input id="tb2" type="text" name="textbox2"> Seeking JavaScript code that wil ...

Issue: Module not found error when using Mongoose in Node.js

I am currently facing an issue while trying to execute this code to add new users to my mongoose database. Each time I attempt to launch my server, I encounter the following error message: Error: Cannot find module '../models/registeruser' Th ...

Best Practices for Using require in Node.js

I have been working on an Express application where I am utilizing Mongoose for data storage. To ensure that my User model (featuring username and password) can be saved properly, I included require('mongoose') in the Models/user-model.js file. ...

Ensure that the submission button also transmits an additional piece of information

My form has a submit button that sends field values to the address bar, but I want it to also add an extra value (&submitted=yes) when clicked. How can I modify my submit button from this: <input type="submit" name="submitted" value="submit"> ...

Improving User Experience with HTML 5 Progress Bars

Has anyone ever tried implementing a progress bar on a Marketo Landing page? The concept is that the progress bar would increase with each completed field until all fields are done, reaching 100% completion? Here is my current code: <progress max="100 ...

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

Select various icons within a div that already has a click event attached to it

Having an issue with a clickable div element. Working on an Ionic 2 audio application where I have a series of divs each containing different icons. Specifically, each div has two icons - one for downloading the audio and the other for playing it. I wan ...

How is the Router module utilized within Express framework?

Apologies if this is a basic inquiry, but despite my efforts to research and consult documentation, I am still unable to grasp the precise function of the Route module and its intended purpose. Can someone provide clarification on this topic? ...

Should one consider using requirejs to enhance individual pages instead of relying solely on vanilla JavaScript applications?

I have a question regarding the practical use of RequireJS. After learning about purely JavaScript-driven web pages, I have been enhancing individually rendered views (often provided by a PHP Framework) with AngularJS to add more functionality. However, m ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...