【发布时间】:2019-07-30 15:14:52
【问题描述】:
Typescript 有这个instanceof checks on custom errors 问题,但不清楚我们需要做什么才能让instanceof 正常工作。例如对于这个异常,我们如何让instanceof 工作:
/**
* @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,这是我正在做的,但是这个测试没有通过:
it("should be an instance of IsError", () => {
let error = new IsError("This is an IsError", 'value');
expect(error instanceof IsError)).toBeTruthy();
});
更正
我在测试...IsError)) 中有一个额外的括号,我误认为测试没有通过。我更新了测试,现在它可以工作了。所以这个问题中的例子IsError实现是正确的。
IIUC 这个实现在 ES5 中不起作用,但是包含 CoreJS 的 AFAIK 客户端可以。
【问题讨论】:
-
不扩展 Error 类而只依赖
Object.setPrototypeOf行会发生什么? -
试过了 - 检查测试仍然没有通过......
-
我创建了一个对我有用的基本示例 (here)。我使用 Typescript 3.0.1。
-
Duh ... 感谢您指出这一点 - 我在开玩笑的测试中多了一个括号,看起来好像测试没有通过。现在一切都好。例子更简单。请把它作为答案发布,我会检查它。
标签: javascript node.js angular typescript