Get properties of a class
This TypeScript code
class A {
private a1;
public a2;
}
compiles to this JavaScript code
class A {
}
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 = "";
}
it compiles to
class A {
constructor() {
this.a1 = "";
this.a2 = "";
}
}
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";
Applied to your example
class Describer {
static describe(instance): Array<string> {
return Object.getOwnPropertyNames(instance);
}
}
let a = new A();
let x = Describer.describe(a);
Some answers are partially wrong, and some facts in them are partially wrong as well.
Answer your question: Yes! You can.
In Typescript
class A {
private a1;
private a2;
}
Generates the following code in Javascript:
var A = /** @class */ (function () {
function A() {
}
return A;
}());
as @Erik_Cupal said, you could just do:
let a = new A();
let array = return Object.getOwnPropertyNames(a);
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:
let className:any = A;
let a = new className();// the members will have value undefined
A general solution will be:
class A {
private a1;
private a2;
constructor(a1:number, a2:string){
this.a1 = a1;
this.a2 = a2;
}
}
class Describer{
describeClass( typeOfClass:any){
let a = new typeOfClass();
let array = Object.getOwnPropertyNames(a);
return array;//you can apply any filter here
}
}
For better understanding this will reference depending on the context.
Another solution, You can just iterate over the object keys like so, Note: you must use an instantiated object with existing properties:
printTypeNames<T>(obj: T) {
const objectKeys = Object.keys(obj) as Array<keyof T>;
for (let key of objectKeys)
{
console.log('key:' + key);
}
}