【问题标题】:Typescript error when adding property to Error object "Property ... does not exist on type 'Error'"向错误对象添加属性时出现打字稿错误“属性...在类型'错误'上不存在”
【发布时间】:2021-10-26 17:05:30
【问题描述】:

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

//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 教程中复制的,所以我想这实际上不是一个好习惯?

【问题讨论】:

  • @HereticMonkey:我认为这是一个不同的用例,因为这本质上是关于修改全局范围。
  • @H.B.我认为这是相同的用例,因为它是关于向内置类型添加属性。但请选择:google.com/…。那里有 46k 条目。
  • @HereticMonkey 不同之处在于,对于全局,您需要调整类型信息以适应任何地方的属性,而这里是一种特殊的类实例,您通常不希望影响所有实例那堂课。但是,是的,可能有大量的重复项适合这个问题。
  • 感谢@HereticMonkey - 我已经发布了我自己的解决方案,专门用于处理 404 错误代码。我假设您链接到的解决方案适用于更一般的用例。

标签: node.js typescript express error-handling


【解决方案1】:

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

在这种情况下,您可以创建自己的 Error 子类,其中包括 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');

【讨论】:

  • status?: number;
  • 这是 TypeScript 中最常见的错误之一。我们还需要关于这个主题的另一个问答对吗?
  • 谢谢@H.B.我已经发布了一个为我解决了问题的解决方案,但假设您的解决方案可以作为一个可行的替代方案,并希望能帮助处于类似情况的其他人!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-03-26
    • 2021-02-19
    • 1970-01-01
    • 2017-11-25
    • 1970-01-01
    • 2018-11-30
    • 2020-10-18
    • 2021-10-23
    • 1970-01-01
    相关资源
    最近更新 更多