The functionality of express types is not optimized in the TypeScript playground

Have you attempted creating a demo for the TS type of express? Follow the Type Acquisition guide of TS Playground to manage the imported types by using // types: npm_tag_or_version.

Despite specifying both versions, none seem to be functioning correctly.

import express, { Request, Response, NextFunction } from 'express'; // types: 4.18.2
// import express, { Request, Response, NextFunction } from 'express'; // types: 4.17.7

const app = express();

const authenticate = (req: Request, res: Response, next: NextFunction) => {
    next();
};

app.post('/create', authenticate, (req: Request, res: Response) => { });

Encountered error message:

No overload matches this call.
  Overload 1 of 2, '(path: PathParams, ...handlers: RequestHandler[]): Express', gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => void' is not assignable to parameter of type 'RequestHandler'.
      Types of parameters 'next' and 'next' are incompatible.
        Type 'NextFunction | undefined' is not assignable to type 'NextFunction'.
          Type 'undefined' is not assignable to type 'NextFunction'.
  Overload 2 of 2, '(path: PathParams, ...handlers: RequestHandlerParams[]): Express', gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => void' is not assignable to parameter of type 'RequestHandlerParams'.
      Type '(req: Request, res: Response, next: NextFunction) => void' is not assignable to type 'RequestHandler'.(2769)

Playground Link

TS version: 5.1.3

Answer â„–1

One solution to the issue is to use an optional parameter next in the function:

import express, { Request, Response, NextFunction } from 'express';

const app = express();

const authenticate = (req: Request, res: Response, next?: NextFunction) => {
    if (next) {
      next();
    }
};

app.post('/create', authenticate, (req: Request, res: Response) => { });

It appears that TS Playground has trouble with the express-serve-static-core types.

When inspecting the type, it refers to @types/express-serve-static-core/index.d.ts

export interface RequestHandler<
    P = ParamsDictionary,
    ResBody = any,
    ReqBody = any,
    ReqQuery = ParsedQs,
    LocalsObj extends Record<string, any> = Record<string, any>
> {
    // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2)
    (
        req: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>,
        res: Response<ResBody, LocalsObj>,
        next: NextFunction,
    ): void;
}

However, when examining app.post, it references express-serve-static-core/express-serve-static-core.d.ts

interface RequestHandler {
  (req: Request, res: Response, next?: NextFunction): any;
}

In my opinion, this discrepancy is a bug in the Playground.

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

Why is my RxJS timer not waiting for the specified time?

I'm diving into the world of RxJS and trying to grasp its concepts. During some testing, I encountered a puzzling issue that has me stumped. Below is the snippet in question : let item = { id: 1, name: 'chair' }; const asyncItem = timer(20 ...

Avoiding the use of HTTPOnly cookie in production sites

Utilizing firebase along with session cookies for user authentication on my react website, with the backend using google cloud functions. Successful login occurs on localhost where my react app runs on localhost:3000 and the cloud functions on localhost:50 ...

Error: The Class 'Subject<T>' does not properly extend the base class 'Observable<T>'

I encountered an error that says: **Build:Class 'Subject<T>' incorrectly extends base class 'Observable<T>** . I have TypeScript 2.4.1 installed and obtained angular quick starter files from the GitHub repository angular quick ...

Storing the compiled TypeScript file in the source file's directory with the TypeScript compiler

I am in need of assistance with compiling TypeScript files (ts) into JavaScript files (js) and mapping files (js.map) all within the same directory as the source file. I have attempted to configure this in my tsconfig.json file using: { "compilerOption ...

The proxy request gets delayed unless I utilize the http-proxy-middleware

Here is the code for a provider: @Injectable() export class GameServerProxyService { private httpProxy: httpProxy; constructor(@Inject(GameServerDetailsService) private gameServiceDetailsService: GameServerDetailsService) { this.httpP ...

What is the process for obtaining the feedback from a new StepFunctionsStartExecution operation using AWS CDK?

Task Explanation: Iterate through the children in Step Function 1 Forward each JSON object to Step Function 2 Upon completion of Step Function 2, a response is obtained from an external API Utilize this API response within Step Function 1 Visual Represen ...

Journey Swiftly Control

I have a question. Is it possible to manipulate routes in Express? Can I assign multiple routes to the same get or post request when providing an address? module.exports = function (app) { var controller = app.controllers.maps.cliente; app.route(&apos ...

I am encountering an issue with the connection between my Node.js web application and a MongoDB Atlas cluster

I encountered an issue with my MongoDB cluster. Initially, I connected my Node.js Express application to my MongoDB Atlas cluster, but it was not functioning correctly (I suspect the error originated from the MongoDB Atlas cluster because switching the con ...

Node.js using Express: Modifying response data for specific route

I've searched through numerous resources but haven't been able to find a solution, so I'm reaching out for some assistance! :) I have developed a UI5 Application using Node.js with Express on the server-side. The data is retrieved from a SQ ...

Pretend to be a socket using Socket.IO

Context: Currently, I am utilizing Express, http.Server, and Socket.IO to develop a game. With each connection established, a socket session is created through which server-client communication occurs. My goal now is to incorporate AI into the game to enh ...

Locate a specific document using its object ID within a MongoDB collection using Node.js and Express.js

Hey, I'm having trouble fetching the products of a specific user. I added the user's Object ID in the model, but I'm stuck on how to set up the router callback function! { "_id": { "$oid": "62f250d3e2533c ...

Adding a service into a guard in Nest.JS

My KeysModule allows me to add or remove API keys that I need to protect certain routes from unauthorized access. To achieve this protection, I have implemented an ApiGuard: import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common&ap ...

Redirect user to the "Confirm Logout" page in Keycloak after refreshing the page before logging out

While working on a project with keycloak, I've encountered an issue that I can't seem to figure out. After logging in and navigating to my project's page, everything operates smoothly. However, if I happen to refresh the page before logging ...

Upon attempting to start the server, the module 'express-stormpath' could not be located

Upon trying to execute node server.js (in a regular terminal without superuser or root permissions), the following error is thrown: alphaunlimitedg@AUNs-PC:~/my-webapp$ node server.js module.js:442 throw err; ^ Error: Cannot find module 'expr ...

Updating or adding an object property in an ExpressJS module

When creating a module on express, I encountered an issue that I couldn't figure out. Here is the first code snippet: module.exports = { myobj : {}, myfun : function(app) { app.all('/',function (req, res, next) { this.myobj.foo = †...

Is it possible to import a class from a different project or module in TypeScript?

I am attempting to modify the build task in Typescript within this specific project: https://github.com/Microsoft/app-store-vsts-extension/blob/master/Tasks/app-store-promote/app-store-promote.ts I am looking to incorporate an import similar to the one be ...

Node.js: The choice between returning the original Promise or creating a new Promise instance

Currently, I am in the process of refactoring a codebase that heavily relies on Promises. One approach I am considering is replacing the new Promise declaration with simply returning the initial Promise instead. However, I want to ensure that I am correctl ...

Can you explain how to incorporate global functions from a javascript library into an Angular 2 project?

Recently I started working with angular-cli and came across a situation where I have an index.html containing a javascript script with some global functions. I want to access these functions in multiple parts of my application. As someone who is new to A ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

Identifying Gmail line breaks in the clipboard using Angular

I'm currently working on a feature that allows users to paste content from Gmail into a field and detect line breaks. The field doesn't have to be a text area, I just need to identify the line breaks. However, there seems to be an issue with det ...