Typescript 类型脚本类型检查抽象类
假设我有一个这样的抽象类Typescript 类型脚本类型检查抽象类,typescript,express,Typescript,Express,假设我有一个这样的抽象类 abstract class AppException extends Error { // constructor, functions, whatever } 也就是说我有一门课 class NotFoundException extends AppException { } 现在我在一个随机函数中有一个类型为error的对象错误。我将NotFoundException的实例传递给函数 在错误中,如果我尝试 if (error instanceof A
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
typescript中的类型有什么问题吗
注意:我使用此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()}`);
}
},
);
抽象类AppException扩展错误{}
类NotFoundException扩展AppException{}
异步函数getRegisterController(
请求:,
res:答复,
下一步:NextFunction,
):承诺{
//业务逻辑
下一步(newnotfoundexception('User notfound');
返回;
}
这个是.server.use(
(err:Error、req:Request、res:Response、next:NextFunction)=>{
if(AppException的错误实例){
//他不在这里工作
error(`AppException状态代码${err.getStatusCode()}`);
}
},
);
这是我在expressjs中使用的两个中间件函数。此inturn调用另一个中间件并将我作为错误对象发送的对象传递。您提供的代码看起来正确,唯一的例外是您需要
instanceof
(全部小写):
抽象类AppException扩展错误{}
类NotFoundException扩展AppException{}
const error=new NotFoundException();
常数测试=()=>{
if(AppException的错误实例){
返回“某物”;
}
返回“其他事物”;
};
log(test())//在控制台中打印“某物”
您t配置的目标可能是
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);
检查以获取更多信息我的代码中确实有
instanceof
。我在这里键入时输入了错误。它也不适用于此。@SriramR此答案表明错误存在于您的代码中。您尚未发布的代码。您认为您正在传递AppException实例,但您没有。如果您这样做,它将返回“something”,正如这个答案所证明的。你的答案的一个问题是,我的函数接受一个类型为error的error参数。在你的答案中,error对象的类型是NotFoundException,这就是我要传递的,但函数接收到的错误是error
对象。@SriramR。同样,问题在于你没有发布的代码如果你不发布一个完整的复制问题的最小示例,就无法帮助你发现错误。哦,是的,我理解。让我发布一个真实的示例。你的问题不是关于TypeScript,而是关于ExpressJS。使用适当的标记。可能是