为什么 typescript 中的 instanceof 没有按预期工作?

use*_*351 1 javascript prototype 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个更新抽象方法:

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.`);
        }
      ....
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我试图捕获错误,然后获取它的实例,如下所示:

} catch (e) {
            const statusCode = (e instanceof StreamNotFound) ? 404 : null;
            throw HttpController.handleError(e, statusCode);
        }
Run Code Online (Sandbox Code Playgroud)

但 statusCode 将始终返回 null,即使 StreamNotFound 扩展了 NotFound,并且 Update 抽象方法正在使用 Notfound。

正如您所看到的,我Object.setPrototypeOf(this, StreamNotFound.prototype);在每个方法上添加了 ,所以我想知道为什么它没有按预期工作?

esq*_*qew 5

子类始终是其instanceof自身及其任何父类。然而,反之则不然:父类不是instanceof它的任何子类。

在此示例中,StreamNotFound instanceof NotFound === true. 然而,父类显然不是 instanceof它的任何子类。这里,NotFound instanceof StreamNotFound === false

在你的控制器中,你正在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));
Run Code Online (Sandbox Code Playgroud)