`Express routes in TypeScript`

Recently, I have been following a tutorial on how to build a Node.js app with TypeScript. As part of the tutorial, I attempted to organize my routes by creating a separate route folder and a test.ts file containing the following code:


import {Router} from "express";

let router = Router();
router.get('/', get);

export async function get(req, res, next) {
    try {
        res.send("Testing...");
    } catch (err) {
        console.log('err', err);
        next(err);
    }
}

export {router};

I then tried to integrate this route into my server.ts file like so:


import * as express from "express";
import * as TestRoute from './routes/test';

class App {
    public express : express.Application;

    constructor() {
        this.express = express();
        this.mountRoutes();
    }

    private mountRoutes() : void {
        const routes: express.Router = express.Router();
        routes.use('/test', TestRoute);
        this.express.use('/', routes);
    }
}

export default new App().express;

However, when using routes.use('/test', TestRoute);, TypeScript raised an error indicating that the types were not assignable. The error message specifically mentioned the missing 'includes' property.

I am seeking help in understanding and resolving this error. Additionally, I would appreciate any guidance on structuring routes and incorporating them into TypeScript applications. My current TypeScript version is 2.7.

Answer №1

Your issue lies in the import statement within the server.ts file, specifically in how you are utilizing the module.

Upon examining the TestRoute object, it appears to function solely as a module that encapsulates all your exported content. Therefore, you must find a way to access the router object within it. There are two possible solutions:

  1. Modify your import statement in server.ts to read as follows:
    import { router as TestRoute } from './routes/test';
  2. Alternatively, adjust how you access the module in your routes.use line by using this syntax instead:
    routes.use('/test', TestRoute.router);

You can choose either approach, as both will resolve the issue, but remember to implement only one of them!

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

How can I set a header to be automatically included in every "render" response in Node.js/Express?

One of the challenges I face involves implementing "controllers" in my code: app.get('/',function(req,res){ var stuff = { 'title': 'blah' }; res.render('mytemplate',stuff); }); In particular, I'm worki ...

Basic Node.js application for retrieving a response

Snippet of Express Code: Database Query In this piece of code, I am attempting to pass the table name as keyName, extracted from the request. However, I am encountering a deadlock issue. I want to confirm if I am following proper protocols for JSON resp ...

"Can you share a method to extract the value from a TextField component in a React hook-based Material-

Currently, I am using Material-UI within a React project and have a component set up like this: const UserDetail = (props: ListDetailProps) => { const oldpassword = useRef<TextFieldProps>(null); const newpassword = useRef<TextFieldProps ...

Utilizing Generic Types for Object Parameters

Why am I encountering an error when trying to use a function of type A for a B type one? How can I define a function type with unknown properties? When I attempt to define props in type B as props: Record<string, unknown>, it results in a similar err ...

I am facing difficulties in inserting information into the MongoDB database

I've encountered an issue while trying to add user data to my MongoDB database locally using post requests on Postman. Despite having an API set up in the userRoute file to handle these requests, no data is being added. Below is the code snippet: cons ...

After compiling, global variables in Vue.js 2 + Typescript may lose their values

I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts file that I need to access globally throughout my project: // ... Vue.prototype.$http = http; // This library is imported from another file and ...

Tips for sorting/merging/consolidating data in Angular

Take a look at this code snippet: rowData = [ [ '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2019-12-10 08:00:00', '2018-12-10 08:00:00' ...

Does the isAuthenticated() method of Passport always indicate a false authentication?

Currently encountering an issue with Passport while attempting to transition from my original authentication method, as Passport supports other methods like Google and GitHub. Despite extensively researching and trying to implement local authentication, it ...

Exploring Angular 7: Leveraging class inheritance and the powerful httpClient

It has come to my attention that my services are quite repetitive. In an attempt to enhance them, I decided to delve into super classes and inheritance in Angular. However, I have been struggling with the constructor and super calls. Despite TypeScript com ...

I'm baffled as to why TypeScript isn't throwing an error in this situation

I anticipated an error to occur in this code snippet, indicating that b.resDetails is possibly undefined, however, no such error occurred. Can someone please provide an explanation for this unexpected behavior? I'm quite perplexed. type BasicD ...

Animating Angular ng-template on open/close state status

I am looking to add animation when the status of my ng-template changes, but I am unable to find any information about this component... This is the code in my report.component.html <ngb-accordion (click)="arrowRotation(i)" (panelChange)="isOpen($even ...

Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators. Here is our old code snippet: const ADD_NAME = 'ADD_NAME'; /** * Se ...

Prevent coverage tracking for files or paths enclosed in square brackets in jest

I am trying to exclude a specific file from test coverage in Jest by modifying the collectCoverageFrom array. The file name contains square brackets, and I have added an entry with a negation for this file. collectCoverageFrom: [ './src/**/*.{js ...

When an event occurs, have Express make an HTTP call to Angular

In the process of developing an Angular application, I am working on a feature that will enable around a thousand users to connect simultaneously in order to book tickets. However, I only want a specific number of them, let's call it "XYZ", to access ...

Looking for a quick guide on creating a basic RESTful service using Express.js, Node.js, and Mongoose?

As a newcomer to nodejs and mongoDB, I've been searching high and low on the internet for a tutorial that combines express with node and mongoose. What I'm specifically looking for is how to use express's route feature to handle requests and ...

Every time I attempt to utilize tokens, I consistently encounter the error message "Login sessions require session support"

Currently, I am learning about JSON tokens through a tutorial and encountering an error. Previously, everything was functioning correctly with sessions, but now I can't seem to pinpoint the problem even though I'm using identical code. This snip ...

How can I effectively filter the data returned by consuming an API in JSON through an Angular service?

My Angular 6 project includes a UsersService that is injected into the UsersComponent. Originally, the component displayed mock data in the form of a string array. However, it now consumes JSON data from an API provided by JSONPlaceholder via the UsersSer ...

Can you explain the significance of the res.render callback parameter in Express 4.0 for Node.js?

Can you explain the role of the res.render callback argument? When would it be necessary to use this callback argument, especially when there is already a template specified as the first argument? The following code snippet is taken from the official doc ...

Steps for incorporating a filter feature in an Angular Material table

.HTML: Can someone assist me with implementing a filter in this component? I tried using it with the expansion table, but unfortunately, the filter is not working as expected. <mat-dialog-content style="width: 63rem; overflow: initial;"&g ...

Designing a schema for storing bus locations using Mongoose

I have a project underway to create a bus ticket booking application using node.js. One of the challenges I'm facing is designing a location schema that will dynamically populate the "to-location" dropdown with options excluding the "from-location" sp ...