Typescript 如何在非静态getter中使用'newthis'?

Typescript 如何在非静态getter中使用'newthis'?,typescript,class,inheritance,instance,getter,Typescript,Class,Inheritance,Instance,Getter,我试图从静态和常规getter中创建父类的新实例。这适用于静态getter,但不适用于常规getter class Example { static get clone() { return new this(); } get clone() { return new this(); } } 其中,在上使用示例时,此有效,但导致无法从此类扩展 class Example { static get clone() { return new Exampl

我试图从静态和常规getter中创建父类的新实例。这适用于静态getter,但不适用于常规getter

class Example {
  static get clone() {
    return new this();
  }
  get clone() {
    return new this();
  }
}
其中,在
上使用
示例
时,此
有效,但导致无法从此类扩展

class Example {
  static get clone() {
    return new Example();
  }
  get clone() {
    return new Example();
  }
}

如何在非静态getter中使用
新this

如果我理解正确,您正在寻找:

class Example {
  static get clone() {
    return new this();
  }
  get clone() {
    const copy = new (this.constructor as any)();
    Object.assign(copy, this);
    return copy;
  }
}
用法:

class Foo extends Example {}

console.log(
    Example.clone,
    new Example().clone,
    Foo.clone,
    new Foo().clone
)

如果我理解正确,您正在寻找:

class Example {
  static get clone() {
    return new this();
  }
  get clone() {
    const copy = new (this.constructor as any)();
    Object.assign(copy, this);
    return copy;
  }
}
用法:

class Foo extends Example {}

console.log(
    Example.clone,
    new Example().clone,
    Foo.clone,
    new Foo().clone
)

只需
按此返回副本
只需
按此返回副本