我正在使用express和TypeScript項(xiàng)目為node.js構(gòu)建一個(gè)錯(cuò)誤處理中間件。在其中我有一個(gè)AppError擴(kuò)展的類Error。它看起來(lái)像這樣: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,? ? };? }}我目前正在使用以下中間件將其放入new AppError()一條路線中:/errorerrorHandlerfunction 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);}在中間件內(nèi)部,我試圖AppError在err[[Prototype]] 鏈上查找,但在 TypeScript 代碼中驗(yàn)證總是失敗。然而,用 Babel 轉(zhuǎn)譯它并用 運(yùn)行 JS 版本后node,err instanceof AppError解析為true. 為什么TS代碼里沒(méi)有呢?在上面的示例中,Object.getPrototypeOf(err)返回 me Error {},并將err類型更改為AppErrororany不會(huì)影響結(jié)果。據(jù)我了解,新構(gòu)造的對(duì)象(new AppError()運(yùn)行后)應(yīng)該 [[Prototype]] 鏈接到AppError. curl http://localhost:3333/error在 TS 服務(wù)器上運(yùn)行時(shí),我得到{ "internalCode": 1, "message": "This is an error", "httpCode": 500 },這意味著它err確實(shí)是由AppError().
TypeScript 類繼承的行為與其 ES6 等效項(xiàng)不同
繁花如伊
2023-08-05 19:38:23