简体   繁体   中英

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. This class will be extended by Angular components who will pass various classes. 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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