MrMamen
MrMamen

Reputation: 389

Getting keys of a class in typescript

I have a class with a lot of methods let's call it myClass. I'm calling it like this:

myClass[key]()

Is there a way to get the possible values from key? I hoped for something like keyof myClass, but I got 'myClass refers to a value, but is being used as a type here'

The problem is probably that as of now myClass is defined in a .js-file and encapsulated like this:

const myClass = new MyActualClass();
export default myClass

Is it possible to extract the information without converting the .js file to typescript, and extract the information from MyActualClass directly?

Upvotes: 3

Views: 12796

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074485

To get the runtime property names, you can use Object.keys or Object.getOwnPropertyNames.

At the TypeScript level, if you wanted to declare a variable that could contain the keys for an instance of your class, you'd do it like this:

let s: keyof typeof myClass;

Example on the playground

Upvotes: 6

Related Questions