在打字稿中获取类的键 [英] Getting keys of a class in typescript
问题描述
我有一个带有很多方法的类,我们称之为myClass.我这样称呼它:
I have a class with a lot of methods let's call it myClass. I'm calling it like this:
myClass[key]()
是否有办法从键中获取可能的值?我希望像myClass的keyof这样的东西,但是我得到了"myClass指向一个值,但是在这里被用作类型"
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'
问题可能是,到目前为止,myClass已在.js文件中定义并像这样封装:
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
是否可以在不将.js文件转换为打字稿的情况下提取信息,并直接从MyActualClass提取信息?
Is it possible to extract the information without converting the .js file to typescript, and extract the information from MyActualClass directly?
推荐答案
要获取运行时属性名称,可以使用Object.keys
或Object.getOwnPropertyNames
.
在TypeScript级别,如果您想声明一个可能包含类实例的键的变量,您将像这样进行操作:
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;
这篇关于在打字稿中获取类的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!