문제는 Javascript의 내장 클래스 Error가 this호출 할 때 생성 할 객체 (예 :) 를 새롭고 다른 객체 로 전환하여 프로토 타입 체인을 끊고 super새 객체에 예상되는 프로토 타입 체인이없는 경우, 즉 인스턴스라는 것입니다. 의 Error하지 않는 CustomError.
이 문제는 Typescript 2.2부터 지원되는 'new.target'을 사용하여 우아하게 해결할 수 있습니다. https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html 참조
class CustomError extends Error {
constructor(message?: string) {
super(message);
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); }
else { this.__proto__ = actualProto; }
}
}
사용하면 new.target여기에 제안 된 다른 답변처럼 프로토 타입을 하드 코딩 할 필요가 없다는 장점이 있습니다. 이는 상속 된 클래스 CustomError가 자동으로 올바른 프로토 타입 체인을 얻는다는 장점이 있습니다 .
프로토 타입을 하드 코딩하면 (예 :) Object.setPrototype(this, CustomError.prototype), CustomError자체적으로 작동하는 프로토 타입 체인을 가지지 만에서 상속하는 모든 클래스 CustomError가 손상됩니다. 예를 들어 a의 인스턴스가 예상대로 class VeryCustomError < CustomError되지 않고 .instanceof VeryCustomErrorinstanceof CustomError
참조 : https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200