网站搜索

javascript - Typescript 代码无法使用 commonjs 风格的 require 语句


我对 Typescript、Node 以及 Express 都是新手。我按照这里的描述完全设置了我的项目:https://linux-console.net/community/tutorials/setting-up-a-node-project-with-typescript

这是我尝试运行的代码,是我从那个链接得到的:

import express from 'express';

const app = express();
const port = 3000;
app.get('/', (req, res) => {
  res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, err => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

当我尝试使用 npm start 运行这段代码时,我得到这个错误:No overload matches this call. The last overload gave the following error. Argument of type '(err: any) => void' is not assignable to parameter of type '() => void'.ts(2769) 我检查了 .d.ts 文件,发现回调函数不接受任何参数。有人在这里遇到过同样的问题:express typescript err throw 'any' warning

然后我阅读了我从中获得这篇帖子的原始帖子的评论,有人提到如果他们将第一行从 import express from 'express'; 改为 var express=require('express');,代码就能工作。为什么会这样?我还必须明确指定 req、res 和 err 的类型为 any 才能使其工作。这是最终可行的代码:

var express = require('express');

const app = express();
const port = 3000;
app.get('/', (req: any, res: any) => {
  res.send('The sedulous hyena ate the antelope!');
});
app.listen(port, (err: any) => {
  if (err) {
    return console.error(err);
  }
  return console.log(`server is listening on ${port}`);
});

答案#1

当你遇到 No overload matches this call. 错误时,意味着你定义了该类型中不存在的参数。

在你的情况下,你在 listen 回调中使用了 err 参数,这不应该存在(参见 http://expressjs.com/en/api.html 中的 app.listen)

要修复 ts 错误,只需删除下面的 err 及相关代码。

关于你的导入,我建议使用更新的语法而不是旧的 require(现在应该可以正常工作了)。

最后但同样重要的是,尽量避免将你的类型设置为 any,因为那就像拥有一个没有电池的火灾报警器。你需要的类型是 Express 内置的类型,你可以这样定义它们:

app.get('/', (req: express.Request, res: express.Response) => {
  res.send('The sedulous hyena ate the antelope!');
});