问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/58130794/getting-keys-of-a-class-in-typescript