首页 > 解决方案 > 为什么我没有得到我的泛型的属性?

问题描述

我目前拥有的是一个表,它用于不同的组件,根据使用的位置,它将具有固定的定位行集(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`

标签: typescripttypescript-typingstypescript-generics

解决方案


编译器倾向于急切地评估未解析的泛型类型的属性访问或函数调用;这意味着当你写的时候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

Playground 代码链接


推荐阅读