Home > other >  How should I give the parameters to express.use without getting a type error?
How should I give the parameters to express.use without getting a type error?

Time:03-23

In this code snippet in the use function the path string throws this error.

Argument type string is not assignable to parameter type RequestHandler<RouteParameters>
   Assigned type doesn't contain call signatures

How should I use the params properly?

const express = require('express');

const app = express();

app.use('/test', (req, res, next) => {
    res.send('<h1>Test</h1>');
});

app.use('/', (req, res, next) => {
    res.send('<h1>Hello World</h1>');
});

app.listen(3000);

CodePudding user response:

Everything seems to be correct, but 1 thing that's bugging me is the way you are importing express. If you are using typescript you should be importing like this

import express from 'express'

CodePudding user response:

It seems like you're mixing commonjs modules with typescript/es6 modules. They are compiled differently. This is why you're gettings this error, because when you required express, it was not resolved to the correct function that can be executed for you get a instance of express app.

In order make compatibility between different types of modules, you must configure typescript.

{
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "target": "es6",
        "moduleResolution": "node",
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*"
            ]
        }
    },
    "include": [
        "src/**/*"
    ]
}
  • Related