Is there a way to get properties names of class in TypeScript: in the example I would like to 'describe' the class A or any class and get an array of its properties (maybe only public one ?), 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'] */
Just for fun
Update: If you are using custom constructors, this functionality will break.
Another solution, You can just iterate over the object keys like so, you must instantiate the object first:
Some answers are partially wrong, and some facts in them are partially wrong as well.
Answer your question: Yes! You can.
In Typescript
Generates the following code in Javascript:
as @Erik_Cupal said, you could just do:
But this is incomplete. What happens if your class has a custom constructor? You need to do a trick with Typescript because it will not compile. You need to assign as any:
A general solution will be:
For better understanding this will reference depending on the context.
This TypeScript code
compiles to this JavaScript code
That's because properties in JavaScript start extisting only after they have some value. You have to assign the properties some value.
it compiles to
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()
.Applied to your example