'compile-time' way to get all property names defined interface

后端 未结 4 1370
心在旅途
心在旅途 2020-12-03 05:00

I\'d like to create a generic TypeScript class for rendering (as a HTML list) of an array of objects which implement a specific interface.

e.g.

4条回答
  •  伪装坚强ぢ
    2020-12-03 05:14

    At runtime all of the type information is erased, so the best you can do is enumerate the properties of one of the objects. This will give you back all properties, even those that were not on the specified interface.

    class GenericListRenderer {
    
        constructor(private items: T[], private className?: string){
    
        }
    
        private getPropertyNames(): string[] {
            var properties: string[] = [];
    
            if (this.items.length > 0) {
                for (var propertyName in this.items[0]) {
                    console.log(propertyName);
                    properties.push(propertyName);
                }
            }
    
            return properties;
        }
    
        render(){
          var propNames: string[] = this.getPropertyNames();
        }
    
    }
    
    class Example {
        constructor(public name: string) {
    
        }
    }
    
    var example = new Example('Steve');
    
    var a = new GenericListRenderer([example]);
    
    a.render();
    

    There is also Object.keys(), which gives you back all of the properties, although it is only supported in IE9 and above.

    If you can supply more of a use case for what you want to do with the properties, it may be possible to give you an alternate solution using attributes or some other mechanism.

提交回复
热议问题