我有一个Exception1
扩展 Error
的类JavaScript 类,除此之外它还实现了一个接口(interface) SampleInterface
interface SampleInterface {
func(): string;
}
class SampleClass {
public message: string;
constructor(message: string) {
this.message = message;
}
}
class Exception1 extends Error implements SampleInterface {
constructor(message: string) {
super(message);
}
public func(): string {
return "Exception1"
}
}
执行 console.log(new Exception1('a').func())
时在控制台中我收到此错误
Uncaught TypeError: (intermediate value).func is not a function
at <anonymous>:1:33
但是,如果该类扩展了其他类(例如),这将按预期工作
class Exception2 extends SampleClass implements SampleInterface {
constructor(message: string) {
super(message);
}
public func(): string {
return "Exception2"
}
}
执行 console.log(new Exception2('a').func())
时我得到了预期的输出 Exception2
最佳答案
当您扩展 Array
、Error
或 Map
等内置类型时,原型(prototype)链有点困惑,您可以需要显式修复,以便类中定义的成员可供类的实例使用。 TypeScript docu中指出了这一点.
因此,为了解决此问题,您需要执行如下操作:
interface SampleInterface {
func(): string;
}
class Exception1 extends Error implements SampleInterface {
constructor(message: string) {
super(message);
// Explicitly fix the prototype chain
Object.setPrototypeOf(this, Exception1.prototype);
}
public func(): string {
return "Exception1"
}
}
console.log(new Exception1('a').func()) // and now it works
关于javascript - 在 TypeScript 中扩展 Error 类时,接口(interface)不被应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49966806/