打字稿类型检查抽象类

时间:2019-09-07 05:57:59

标签: typescript express

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

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

我们也说我有一个类似的课程

class NotFoundException extends AppException {
}

现在,我在随机函数中遇到类型为Error的对象错误。我将NotFoundException的实例传递给该函数。

在错误中,如果我尝试做

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

如果确定已将otherThing传递给接受类型为NotFoundException的对象的函数,则if语句中的表达式返回false,并返回Error

我正在处理打字稿中的类型有什么问题吗?

注意:我正在使用此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()。依次调用其他中间件并传递我作为错误对象发送的对象。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您的tsconfig目标可能是ES5。自typescrtipt>=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以获得更多信息