我有以下代码:
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",
为什么我的错误实际上不是错误的子类?
// _1 is compiled suffix
ex_1 instanceof Error //true
ex_1.__proto__ // name: Error
对于那些来这里的人。
我喜欢这是解决方案:
export class PutTimeEntryValidationError extends Error {
constructor(message: string, public errors: PutTimeEntryError[]) {
super(message);
// Fix prototype:
Object.setPrototypeOf(this, PutTimeEntryValidationError.prototype);
}
}
显然,转换为 ES5 会破坏这一点。