• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

在打字稿获取类的键

用户头像
it1352
帮助1

问题说明

我有一个带有很多方法的类,我们称之为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?

正确答案

#1

要获取运行时属性名称,可以使用Object.keysObject.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;

实施例在游乐场

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tanhcfiggj
系列文章
更多 icon
同类精品
更多 icon
继续加载