【问题标题】:Writing a generic clone method in TypeScript在 TypeScript 中编写通用克隆方法
【发布时间】:2019-05-27 20:09:23
【问题描述】:

在 TypeScript 中,有没有一种方法可以让类在子类化时引用其构造函数?

abstract class Base<T> {
  constructor(readonly value: T) {}

  abstract getName(): string;

  clone() {
    const Cls = this.constructor;
    return new Cls(this.value);
  }
}

在这个 sn-p 中,Cls 被赋予了 Function 类型,因此编译器抱怨:“不能将 'new' 用于类型缺少调用或构造签名的表达式。”

【问题讨论】:

    标签: typescript


    【解决方案1】:

    Typescript 不对构造函数使用严格类型(它只使用 Function),并且由于这不是构造函数,因此不能使用 new 调用。

    简单的解决方案是使用类型断言:

    abstract class Base<T> {
        constructor(readonly value: T) { }
    
        abstract getName(): string;
    
        clone() {
            // Using polymorphic this ensures the return type is correct in derived  types
            const Cls = this.constructor as new (value: T) => this;
            return new Cls(this.value);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-02
      • 2017-02-11
      • 1970-01-01
      • 2021-01-07
      • 2019-11-27
      • 2018-08-20
      • 2018-02-26
      相关资源
      最近更新 更多