【问题标题】:Typescript typechecking abstract class打字稿类型检查抽象类
【发布时间】:2019-09-07 05:57:59
【问题描述】:

假设我有一个像这样的抽象类。

abstract class AppException extends Error {
  // constructor, functions, whatever   
}

假设我有一个类似的课程

class NotFoundException extends AppException {
}

现在我在随机函数中有一个Error 类型的对象错误。我将NotFoundException 的实例传递给函数。

在错误中,如果我尝试这样做

if (error instanceof AppException) {
return something;
} 
return otherThing;

if 语句中的表达式返回 false,当我确定已将 NotFoundException 传递给接受 Error 类型对象的函数时,它返回 otherThing

打字稿中的类型有什么问题吗?

注意:我正在使用此 AppException 将错误传播到 ExpressJS 中的全局错误处理程序。

编辑: 这就是我正在尝试做的事情

abstract class AppException extends Error {}
class NotFoundException extends AppException {}

async function getRegisterController(
    req: Request,
    res: Response,
    next: NextFunction,
): Promise<Response | undefined> {
    // business logic
    next(new NotFoundException('User not found');
    return;
 }

 this.server.use(
    (err: Error, req: Request, res: Response, next: NextFunction) => {
        if (err instanceof AppException) {
           // doens't work here
           logger.error(`AppException status code ${err.getStatusCode()}`);
        }
    },
);

这是我在 expressjs 中使用的两个中间件函数。在getRegisterController 中,我正在调用next() 并将NotFoundException 的一个实例传递给next()。这反过来调用其他中间件并将我发送的对象作为错误对象传递。

【问题讨论】:

标签: typescript express


【解决方案1】:

您提供的代码看起来正确,唯一的例外是您需要instanceof(全部小写):

abstract class AppException extends Error {}

class NotFoundException extends AppException {}

const error = new NotFoundException();

const test = () => {
  if (error instanceof AppException) {
    return "something";
  }
  return "otherThing";
};

console.log(test()) // Print "something" in the console

TypeScript playground

【讨论】:

  • 我的代码中有instanceof。我在这里打字的时候打错了。它也不适用于此。
  • @SriramR 这个答案表明该错误存在于您的代码中。您尚未发布的代码。您认为您正在传递 AppException 的一个实例,但事实并非如此。如果你这样做了,它会返回“某物”,正如这个答案所证明的那样。
  • 你的回答有一个问题是我的函数接受了一个错误类型的错误参数。在您的回答中,错误对象的类型为 NotFoundException,这是我要传递的,但该函数将错误作为 Error 对象接收。
  • @SriramR typescriptlang.org/play/index.html#code/…。同样,问题出在您未发布的代码中,如果您不发布重现问题的完整最小示例,我们将无法帮助您找出错误。
  • 哦,是的,我明白了。让我发布一个真实的例子。
【解决方案2】:

您的 tsconfig 目标可能是 ES5。你需要手动设置原型,因为typescrtipt&gt;=2.2 或使用更新的目标。

abstract class AppException extends Error {
  constructor() {
    super();
    Object.setPrototypeOf(this, AppException.prototype);
  }
}

class NotFoundException extends AppException {
  constructor() {
    super();
    Object.setPrototypeOf(this, NotFoundException.prototype);
  }
}

const notFoundException = new NotFoundException();

console.log(notFoundException instanceof AppException);

查看typescript team explanation 了解更多信息

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 2018-11-03
    • 1970-01-01
    • 2016-10-03
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-09
    相关资源
    最近更新 更多