[英]Why is instanceof not working as expected in 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.`);
}
....
在我的 controller 中,我試圖捕捉錯誤,然后得到它的實例,如下所示:
} 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);
在每種方法上,所以我想知道為什么它沒有按預期工作?
子類將始終是其自身及其任何父類的instanceof
。 然而,反之則不然:父 class 不是其任何子類的instanceof
。
在此示例中, StreamNotFound instanceof NotFound === true
。 但是,父 class 明確不是其任何子類的instanceof
。 在這里, NotFound instanceof StreamNotFound === false
。
在您的 controller 中,您正在throw
NotFound
的實例,它永遠不會是instanceof StreamNotFound
,因為它在原型鏈中比它的子類更靠前。
在下面的簡化示例中, Bar
將Foo
擴展為子類,因此:
Foo instanceof Foo === true
Bar instanceof Foo === true
Bar instanceof Bar === true
Foo 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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.