typescript - 为什么我没有得到我的泛型的属性?
问题描述
我目前拥有的是一个表,它用于不同的组件,根据使用的位置,它将具有固定的定位行集(QA 自动化)。
我正在尝试为表格创建一个通用的这些行,但代码完成没有按预期工作。我错过了什么?
class Base {
protected myRoot : string
constructor (root : string) {
this.myRoot = root;
}
get base () {
return "base getter"
}
}
class FixedRows1 extends Base {
get id1 () {
return "id1"
}
}
class FixedRows2 extends Base {
get id2 () {
return "id2"
}
}
class FixedTable <T extends typeof Base> extends Base {
private fixedRows : T
constructor (inRoot : string, inFinalLayer : T) {
super(inRoot)
this.fixedRows = inFinalLayer
}
get rows () {
return new this.fixedRows(this.myRoot)
}
}
const layer = new FixedTable("root", FixedRows1);
layer.rows.base // <---- looking to be able to code complete `.example1`, but currently, only code completes `.base`
解决方案
编译器倾向于急切地评估未解析的泛型类型的属性访问或函数调用;这意味着当你写的时候new this.fixedRows(this.myRoot)
,它会扩大this.fixedRows
到它的约束typeof Base
,并因此返回Base
。这没有错,但它没有足够的信息来满足您的目的。如果你想改变它,你可能需要断言返回rows()
其他东西:
get rows() {
return new this.fixedRows(this.myRoot) as InstanceType<T>
}
这里我使用实用InstanceType<T>
程序类型来表示由 type 的构造函数构造的实例的类型T
。
现在它应该按照您想要的方式运行:
const layer = new FixedTable("root", FixedRows1);
layer.rows.id1 // okay
推荐阅读
- c# - 打开和 exe 并保持打开状态 - 独立 exe 可以正常打开
- r - 我可以使用 geom_text 将静态标签添加到 ggplotly 交互式图表吗
- r - 为什么“如果一个对象有两个绑定,一个消失了,引用计数不会回到 1”?
- angular - 我无法在我的 Windows 机器上删除我的全局 angular-cli 版本(1.0.0-beta.28.3)
- jupyter-notebook - Jupyter笔记本崩溃服务器
- sql - 在 SQL 选择语句中使用多个外键
- twilio - Twilio 函数 - 传入参数并格式化 SMS 正文以包含参数
- npm - 在 Azure Pipeline 中安装对等依赖项
- python - 如何在 for 循环的每次迭代中循环显示绘图中的颜色
- python - 如何从 .yuv 视频文件中提取某些帧并使用 FFmpeg、OpenCV 和 python 创建新视频?