简体   繁体   English

如何在Typescript中获得泛型类型的属性

[英]How do you get the properties of a generic type in Typescript

I've created a base class in Typescript that has a generic type and logic to fill a data table. 我在Typescript中创建了一个基类,该基类具有泛型类型和逻辑来填充数据表。 This class will be extended by Angular components who will pass various classes. 此类将由将通过各种类的Angular组件扩展。 I would like to derive the properties of the generic type so I can define the column headers dynamically. 我想派生泛型类型的属性,以便可以动态定义列标题。 How can I get the properties of the class whose type is being used? 如何获取正在使用其类型的类的属性? Please help. 请帮忙。

Below is the bare bones of how I was trying to do it. 下面是我尝试如何做的基本内容。 I was trying to fill displayedColumns with the properties of the Dog or Cat class dynamically: 我试图用Dog或Cat类的属性动态填充displayColumns:

export class MyBaseClass<T>
{
    public displayedColumns: string[] = [];

     constructor()
    {
       let dataItem: T = {} as T;
       Object.keys(dataItem).forEach((key: string) => this.displayedColumns.push(key));
    }
}

export class PetsComponent extends MyBaseClass<Dog>
{

}

export class Dog
{
    public Id: number = 0;
    public Name: string = "";
}

export class Cat
{
    public Id: number = 0;
    public Name: string = "";
}

How can I get the properties of the class whose type is being used? 如何获取正在使用其类型的类的属性?

The types exist only at compile time and are erased at build time when the JavaScript is generated. 这些类型仅在编译时存在,并在生成JavaScript时在构建时删除。 So you should not rely on smart runtime type information from instances of generics. 因此,您不应依赖泛型实例的智能运行时类型信息。

Suggestion 建议

Think in terms of Data instead of Types. 考虑数据而不是类型。 Eg take rows as string[][] (2d array of rows / columns) and leave it up to the classes themselves to parse their data into the required 2d array. 例如,将行作为string[][] (行/列的2d数组),然后将其留给类本身以将其数据解析为所需的2d数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM