Getting keys of a class in typescript

荒凉一梦 提交于 2019-12-13 04:39:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!