繁体   English   中英

TypeScript 类继承的行为与其 ES6 等效项不同

[英]TypeScript class inheritance behaving differently than its ES6 equivalent

我正在为带有 express 和 TypeScript 项目的 node.js 构建一个错误处理中间件。 在其中,我有一个扩展ErrorAppError类。 它看起来像这样:

class AppError extends Error {
  public readonly internalCode: number | undefined;

  public readonly httpCode: number;

  public readonly message: string;

  constructor(httpCode: number, message: string, internalCode?: number) {
    super();
    this.internalCode = internalCode;
    this.message = message;
    this.httpCode = httpCode;
  }

  public generateReport(): GenericReport {
    return {
      code: this.internalCode,
      message: this.message,
    };
  }
}

我目前正在/error路由中抛出new AppError()以使用以下中间件errorHandler捕获它:

function errorHandler(err: Error, request: Request, response: Response, next: NextFunction,): Response {
  if (err instanceof AppError) {
    const report = err.generateReport();

    return response.status(err.httpCode).json(report);
  }

  return response.status(500).json(err);
}

在中间件内部,我试图在err [[Prototype]] 链上找到AppError ,但在 TypeScript 代码中验证总是失败。 但是,在使用 Babel 转译它并使用node运行 JS 版本后, err instanceof AppError解析为true 为什么不在 TS 代码中?

在上面的示例中, Object.getPrototypeOf(err)返回给我Error {} ,将err类型更改为AppErrorany不会影响结果。

据我了解,新构造的对象(在new AppError()运行之后)应该是 [[Prototype]] 链接到AppError 并在 TS 服务器打开的情况下运行curl http://localhost:3333/error ,我得到{ "internalCode": 1, "message": "This is an error", "httpCode": 500 } ,这意味着err是确实是由AppError()创建的。

这个 GitHub 存储库中有一个问题的工作示例。 对此主题的任何澄清将不胜感激。

我看了一下你的代码。 几点意见:

  1. 切换到稍后的 ecmascript 输出可能会解决这个问题,因为您的输出现在不会生成类,因为 EcmaScript 5 还没有它们。
  2. 最好不要使用 ts-node 工具,尤其是当您尝试调试类似的东西时。 它可以提供时髦的结果,并且能够查看正在执行的真实 javascript 是件好事。
  3. 我查看了你的 repo,我相信你应该只使用instanceof来完成你想要做的事情。 我认为就您的错误中间件而言, instanceof 更有意义。

如果你有兴趣,我还写了一个错误处理中间件,它做类似的事情:

https://github.com/curveball/problem/blob/master/src/index.ts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM