javascript - 为什么 instanceof 在 Typescript 中不能按预期工作?
所以我有这些类,我用它们来处理不同场景下的错误,就像这样:
export class APIError extends Error {
public readonly statusCode: number;
public readonly message: string;
constructor(statusCode?: number, message?: string) {
super(message);
Object.setPrototypeOf(this, APIError.prototype);
if (typeof statusCode === 'string') {
message = statusCode;
statusCode = null;
}
this.statusCode = statusCode || 500;
this.message = message || 'Internal Server Error';
}
public toJSON(): JsonData {
return {
statusCode: this.statusCode,
message: this.message,
};
}
}
export class NotFound extends APIError {
constructor(message?: string) {
super(404, 'Not Found');
Object.setPrototypeOf(this, NotFound.prototype);
}
}
export class StreamNotFound extends NotFound {
constructor() {
super('Stream Not Found');
Object.setPrototypeOf(this, StreamNotFound.prototype);
}
}
然后我有这个更新的抽象方法:
public update(id: string, updateThing: T): T {
if (!updateThing) return;
const thing: T = this.get(id);
if (!thing) {
throw new NotFound(`${this.displayName} could not be found.`);
}
....
在我的控制器中,我正在尝试捕获错误,然后像这样获取它的实例:
} catch (e) {
const statusCode = (e instanceof StreamNotFound) ? 404 : null;
throw HttpController.handleError(e, statusCode);
}
但是 statusCode 总是会返回 null,即使 streamNotFound 扩展了 NotFound,而 Update 抽象方法正在使用 NotFound。
如你所见,我在每个方法中都添加了 Object.setPrototypeOf(this, StreamNotFound.prototype);,所以我想知道为什么它没有按预期工作?
答案#1
一个子类总是自身以及其任何父类的 instanceof 实例。然而,反过来则不成立:父类不是其任何子类的 instanceof 实例。
在这个例子中,StreamNotFound instanceof NotFound === true。然而,父类显式地不是instanceof它的任何子类。在这里,NotFound instanceof StreamNotFound === false。
在你的控制器中,你正在 throw 一个 NotFound 的实例,它永远不会是 instanceof StreamNotFound,因为它在原型链上位于其子类之上。
在下面的简化示例中,Bar 作为一个子类继承了 Foo,因此:
Foo instanceof Foo === trueBar instanceof Foo === trueBar instanceof Bar === trueFoo instanceof Bar === false
class Foo {
constructor() {
}
}
class Bar extends Foo {
constructor() {
super();
}
}
const obj1 = new Foo();
const obj2 = new Bar();
console.log("Bar instanceof Bar: " + (obj2 instanceof Bar));
console.log("Bar instanceof Foo: " + (obj2 instanceof Foo));
console.log("Foo instanceof Bar: " + (obj1 instanceof Bar));答案#2
在我的情况下,我有一个根类 NodeCore,有两个类继承了该类:Leaf 和 Choice。我正试图使用一种允许使用任一子类的类型:
type Node = Leaf | Choice;
然后我尝试检查该类型的 instanceof:
if (node instanceof Node) { ... }
这不起作用。但检查 原始类 的 instanceof 是有效的:
if (node instanceof NodeCore) { ... }
