【问题标题】:TypeScript Error for expressJS: No overload matches this callexpressJS 的 TypeScript 错误:没有重载匹配此调用
【发布时间】:2020-11-28 09:33:15
【问题描述】:

注意:我将我的 expressjs 代码转换为 ES6 模块。编译器还没有抱怨,我很惊讶。我假设我们可以做到这一点,而不必使用 .mjs 文件扩展名或将类型模块放在我的服务器文件夹中的 package.json 中?

我正在使用

Node 14.4.0
typescript: 3.9.7

无论如何,回到我的问题。不知道你必须如何输入 expressJS 的东西,例如我在这里得到No overload matches this call

我的意思是,如果它说没有这样的回调,为什么人们会以这种方式使用代码?我很确定这是 app.listen 过去检查此类错误的有效代码

服务器/server.ts

import cluster from 'cluster';

import os from 'os';

import App from './api.js';

const port = process.env.PORT || 3000;

if (cluster.isMaster) {
    for (let i = 0; i < os.cpus().length; i++) {
        cluster.fork();
    }
    console.log('Ready on port %d', port);
} else {
    App.listen(port, (err) => {
        console.log(`express is listening on port ${port}`);
        if (err) {
            console.log('server startup error');
            console.log(err);
        }
    });
}

服务器/api.ts

import historyApi from 'connect-history-api-fallback';
import compression from 'compression';
import countryTable from './data/countries.json';
import express from 'express';
import companyTable from './data/companies.json';
import _ from 'lodash';

const App = express()
.use(compression())
.on('error', (err: any) => {
    console.log(err);
})
.get('/api/v1/countries', (_req: any, res: any) => {
    res.json(countryTable.map((country: any) => _.pick(country, ['id', 'name', 'images'])));
})
.get('/api/v1/companies', (_req: any, res: any) => {
    res.json(
        companyTable.map((company: any) =>
            _.pick(company, [
                'id',
                'active',
                'images',
                'locations',
            ])
        )
    );
})
.use(historyApi())
.use(express.static('dist'))
.use((_req: any, res: any) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,OPTIONS');
    res.header(
        'Access-Control-Allow-Headers',
        'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'
    );
    res.send('Sorry, Page Not Found');
});

export default App;

服务器/tsconfig.json

{
    "extends": "../../tsconfig",
    "compilerOptions": {
        "outDir": "../../dist/server",                        /* Redirect output structure to the directory. */
        "rootDir": "."                         /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    },
    "include": ["./*.ts"],
    "resolveJsonModule": true
}

./tsconfig.json

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    "target": "ES2015",                     /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "es2020",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "lib": ["es5", "es6", "dom"],                      /* Specify library files to be included in the compilation. */
    "moduleResolution": "node",
    "allowJs": true,                     /* Allow javascript files to be compiled. */
//      "checkJs": true,                     /* Report errors in .js files. */
    "jsx": "react",
    "noImplicitAny": true,
    "sourceMap": false,                   /* Generates corresponding '.map' file. */
    "rootDir": "./",                     /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    "removeComments": true,              /* Do not emit comments to output. */
    "strict": true,                      /* Enable all strict type-checking options. */
    "noUnusedLocals": true,                /* Report errors on unused locals. */
    "noUnusedParameters": true,            /* Report errors on unused parameters. */
//    "rootDirs": ["."],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    "typeRoots": [
      "node_modules/@types"
    ],                      /* List of folders to include type definitions from. */
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    "resolveJsonModule": true,
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true
    },
    "include": [
        "src"
    ],
    "exclude": [
        "/node_modules",
        "/src/server",
        "/src/client/js/ink-config.js",
        "**/test",
        "dist"
  ]
}

【问题讨论】:

  • api.js 的来源是什么?另外,为什么这个模块不针对 TypeScript?
  • 不是目标打字稿是什么意思? API 的来源是什么意思?
  • 问题出在app 实例的listen 方法上,该方法来自api.js 模块。所以,我想知道这个方法的代码如何。而且,为什么模块被命名为 api.js(它定义了 JavaScript),而不是一个简单的“api”(没有任何扩展名),它隐式地定义了一个 TypeScript 模块?
  • 让我发布 api.js 以便您了解原因。我将我的 api 逻辑与它的简单服务分离,这很常见。
  • @MarioVernari 查看更新,它显示了 api.js

标签: javascript node.js typescript express


【解决方案1】:

错误告诉您listen() 回调不带任何参数。正确的代码应该是:

App.listen(port, () => {
    console.log(`express is listening on port ${port}`);
});

基本上删除错误参数 (err) 以及与之相关的任何内容,因为它不存在。

错误被on('error') 方法捕获。但是你已经定义了它,所以你应该没问题。

您不能只打印“服务器启动错误”,因为on('error') 方法会捕获所有错误,而不仅仅是服务器启动。但您可以捕获并显示特定错误:

// in api.ts:

.on('error', (err: any) => {
    if (e.code === 'EADDRINUSE') {
        console.log('server startup error: address already in use');
    }
    else {
        console.log(err);
    }
})

这是正确的,不是 typescript 的 express types 中的错误。 Express 只是调用节点的http.Server.listen(),而后者又调用net.Server.listen(),其回调实际上没有传入错误参数。

有关EADDRINUSE 等系统错误列表,请参阅:https://nodejs.org/api/errors.html#errors_common_system_errors

有关 node.js 特定错误的列表,请参阅:https://nodejs.org/api/errors.html#errors_node_js_error_codes

【讨论】:

    猜你喜欢
    • 2022-12-07
    • 2020-06-29
    • 2020-02-15
    • 2021-12-31
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2023-01-04
    相关资源
    最近更新 更多