Typescript是不是要识别Error的子类的实例?

时间:2018-03-08 14:23:18

标签: typescript

我有以下代码:

export class PutTimeEntryValidationError extends Error {
  constructor(message: string, public errors: PutTimeEntryError[]) {
    super(message);
  }
}

try {
   throw new PutTimeEntryValidationError("test",[]);
} catch(ex){
   if (ex instanceof PutTimeEntryValidationError){
      debugger; // 
   } else {
      debugger; // code stops here somehow
   } 
}

我正在使用webpack 3和令人敬畏的打字稿加载器和这个tsconfig.js:

{
    "compilerOptions": {
        "outDir": "./wwwroot/js/", // path to output directory
        "sourceMap": true, // allow sourcemap support
        "noImplicitAny": false, 
        "strictNullChecks": true, // enable strict null checks as a best practice
        "module": "commonjs", // specifiy module code generation
        "jsx": "react",             // use typescript to transpile jsx to js
        "target": "es5", // specify ECMAScript target version
        "allowJs": true, // allow a partial TypeScript and JavaScript codebase
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "lib": [
            "es2015", 
            "es5", //needed for hmr
            "es6",
            "dom"
        ],
        "noUnusedLocals": false
    },
    "include": [
        "./react/**/*"
    ]
}

和:

  "typescript": "^2.4.1",

为什么我的错误实际上不是Error的子类?

// _1 is compiled suffix
ex_1 instanceof Error //true
ex_1.__proto__ // name: Error

1 个答案:

答案 0 :(得分:0)

对于那些来这里的人。

我喜欢这是解决方案:

export class PutTimeEntryValidationError extends Error {
    constructor(message: string, public errors: PutTimeEntryError[]) {
        super(message);

        // Fix prototype:
        Object.setPrototypeOf(this, PutTimeEntryValidationError.prototype);
    }
}

显然是转发到es5打破了这个。