获取类的属性 [英] Get properties of a class

查看:35
本文介绍了获取类的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 TypeScript 中获取类的属性名称?

Is there a way to get properties names of class in TypeScript?

在示例中,我想描述"类 A 或任何类并获取其属性数组(也许只有 public 属性?),是有可能吗?还是应该先实例化对象?

In the example, I would like to 'describe' the class A or any class and get an array of its properties (maybe only public ones?), is it possible? Or should I instantiate the object first?

class A {
    private a1;
    private a2;
    /** Getters and Setters */

}

class Describer<E> {
    toBeDescribed:E ;
    describe(): Array<string> {
        /**
         * Do something with 'toBeDescribed'                          
         */
        return ['a1', 'a2']; //<- Example
    }
}

let describer = new Describer<A>();
let x= describer.describe();
/** x should be ['a1', 'a2'] */ 

推荐答案

此 TypeScript 代码

This TypeScript code

class A {
    private a1;
    public a2;
}

编译为这段 JavaScript 代码

compiles to this JavaScript code

class A {
}

那是因为 JavaScript 中的属性只有在它们具有某些值后才开始存在.您必须为属性分配一些值.

That's because properties in JavaScript start extisting only after they have some value. You have to assign the properties some value.

class A {
    private a1 = "";
    public a2 = "";
}

它编译为

class A {
    constructor() {
        this.a1 = "";
        this.a2 = "";
    }
}

仍然无法从类中获取属性(只能从原型中获取方法).您必须创建一个实例.然后通过调用 Object.getOwnPropertyNames() 获取属性.

Still, you cannot get the properties from mere class (you can get only methods from prototype). You must create an instance. Then you get the properties by calling Object.getOwnPropertyNames().

let a = new A();
let array = return Object.getOwnPropertyNames(a);

array[0] === "a1";
array[1] === "a2";

应用于您的示例

class Describer {
    static describe(instance): Array<string> {
        return Object.getOwnPropertyNames(instance);
    }
}

let a = new A();
let x = Describer.describe(a);

这篇关于获取类的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆