typescript - 在 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 不对构造函数使用严格类型(它只使用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);
}
}
推荐阅读
- algorithm - 如何偏移多边形边缘?
- javascript - 链式类方法抛出“不是函数”错误
- responsive-design - 为什么我在引导卡上添加自己的 CSS 时会失去响应
- flutter - TextFormField 创建键盘以快速打开和关闭
- java - 是否可以在运行时更改 Spring Boot 中 property.file 中的特定值?
- javascript - 如何使用Javascript控制滚动代表高亮效果
- postgis - (Postgrex.Error) 错误 58P01 (undefined_file) $libdir/postgis-2.4
- asp.net-mvc - RadioButton:从视图代码设置焦点不起作用
- git - 如何在 github 中从上游拉取请求
- python - 使用 OpenCV 和 pytesseract 的 Python 实时 OCR