gpt4 book ai didi

typescript - 在 TypeScript 中编写通用克隆方法

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:40 24 4
gpt4 key购买 nike

在 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 不对构造函数使用严格类型(它仅使用 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);
}
}

关于typescript - 在 TypeScript 中编写通用克隆方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56325751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com