将 属性 添加到错误对象 "Property ... does not exist on type 'Error'" 时出现 Typescript 错误

Typescript error when adding property to Error object "Property ... does not exist on type 'Error'"

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

//app.js
const error = new Error('Not Found');
error.status = 404;

当我尝试这个时:

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

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

TypeScript 不允许添加未知属性。有多种方法可以使用任意键定义对象(例如 Record)。

在这种情况下,您可以创建自己的错误子类,其中包括 status 属性.

class StatusError extends Error {
  status: number | undefined;
}

const e = new StatusError('Not found');
e.status = 404;

您也可以将其添加到构造函数中,然后您可以放心地删除 undefined

class StatusError extends Error {
  constructor(public status: number, message?: string) {
    super(message)
  }
}

const e = new StatusError(404, 'Not found');

我发现 expressjs.com documentation 中有一节是关于“我如何处理 404 响应?”,他们提供了这个例子:

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

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

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 };