将属性添加到错误对象“属性...在类型‘错误’上不存在”时出现打字稿错误

Jim*_*ode 8 error-handling node.js express typescript

我正在尝试使用 Node/Express 应用程序转向打字稿。以前我的代码是:

//app.js
const error = new Error('Not Found');
error.status = 404;
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时:

//app.ts
const error = new Error('Not Found');
error.status = 404; // Property 'status' does not exist on type 'Error'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

我从developer.mozilla.org 文档中了解到,Error 构造函数具有以下可选参数:messageoptionsfileNamelineNumber- 所以我想status不应该允许?我想我是从 YouTube 教程中复制的,所以我想这实际上不是一个好的做法?

Jim*_*ode 0

我在expressjs.com 文档中发现有一个关于“如何处理 404 响应?”的部分,其中提供了以下示例:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})
Run Code Online (Sandbox Code Playgroud)

所以我制作了这个并且它已经停止了错误:

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

const app = express();
...

app.use((req: Request, res: Response, next: NextFunction) => {
    res.status(404).send("Sorry can't find that!");
});

export { app };
Run Code Online (Sandbox Code Playgroud)