首页 > 解决方案 > 在 TypeScript 中编写通用克隆方法

问题描述

在 TypeScript 中,有没有办法让一个类在子类化时以一种可以工作的方式引用它的构造函数?

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

  abstract getName(): string;

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

在这个片段中,Cls给出了类型Function,因此编译器抱怨:“不能将'new'与类型缺少调用或构造签名的表达式一起使用。”

标签: typescript

解决方案


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);
    }
}

推荐阅读