为自定义打字稿错误实例实施instanceof检查? [英] Implementing instanceof checks for custom typescript Error instances?

查看:63
本文介绍了为自定义打字稿错误实例实施instanceof检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Typescript具有自定义错误检查实例问题,但尚不清楚我们需要做以使instanceof工作.例如,对于此异常,我们将如何使instanceof工作:

Typescript has this instanceof checks on custom errors issue, but it's not clear what we need to do to get instanceof working. For example for this exception how would we get instanceof working:

    /**
     * @param message The error message
     * @param value The value that violates the constraint
     * @param field The name of the field
     * @param type The expected type for the field
     * @param constraint The name of the constraint violated
     * @param code The application or module code for the error
     */
    export class IsError extends Error {
      constructor(
        public message:string,
        public value: any, 
        public field?:string, 
        public type?: string,
        public constraint?: string,
        public code?:string) {
          super(message);
          this.name = 'IsError';
          Object.setPrototypeOf(this, IsError.prototype);      
      }
    }

此链接表示我们可以手动调整原型,这是我正在做的,但是此测试未通过:

This link says we can manually adjust the prototype, which is what I'm doing, but this test is not passing:

it("should be an instance of IsError", () => {
   let error = new IsError("This is an IsError", 'value');
   expect(error instanceof IsError)).toBeTruthy();
});

更正

我在测试...IsError))中有一个附加括号,我误认为该测试未通过.我更新了测试,现在可以正常工作了.因此,此问题中的示例IsError实现是正确的.

Correction

I had an additional parenthesis in the test ...IsError)) that I mistook for the test not passing. I updated the test and now it work. So the example IsError implementation in this question is correct.

IIUC的这种实现在ES5中不起作用,但是包括CoreJS的AFAIK客户端也可以.

IIUC this implementation will not not work in ES5, but AFAIK clients that include CoreJS will be ok.

推荐答案

代码中的错误(如您正确指出的那样)是断言中的多余括号.

What goes wrong in your code (as you correctly pointed out) was an extra parenthesis in your assertion.

为了完整起见,一个可行的最小示例如下:

Just to be complete, a working and minimal example would look like this:

class CustomError extends Error {
    constructor() {
        super();

        Object.setPrototypeOf(this, CustomError.prototype);
    }
}

let error = new CustomError();

console.log(error instanceof CustomError); // Will log 'true'

这篇关于为自定义打字稿错误实例实施instanceof检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆