Categories
TypeScript Answers

How to get properties of a class with TypeScript?

Spread the love

Sometimes, we want to get properties of a class with TypeScript.

In this article, we’ll look at how to get properties of a class with TypeScript.

How to get properties of a class with TypeScript?

To get properties of a class with TypeScript, we can create an instance of it and then use Object.getOwnPropertyNames on the instance.

For instance, we write

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

const a = new A();
const array = Object.getOwnPropertyNames(a);

to create an A instance.

Then we call Object.getOwnPropertyNames with A instance a to get all the non-inherited properties’ names’ in the array.

Conclusion

To get properties of a class with TypeScript, we can create an instance of it and then use Object.getOwnPropertyNames on the instance.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *