javascript - How can I get properties of a type as an array in Typescript?
问题描述
Given the following type:
class Foo {
constructor(
private one: string,
private two: string,
private three: string) {
}
}
How can I have an array whose values are the type's properties?
e.g. I need to be able to get an array as:
['One', 'Two', 'Three']
Note I need to have the properties extracted from a type and not an instance otherwise I could simply use Object.keys(instanceOfFoo)
.
解决方案
You can use Reflect.construct()
to get the keys, then use Object.keys()
to convert that to an array.
Note: if the key doesn't have a default it won't be generated as you can see with four
.
class Foo {
constructor() {
this.one = ''
this.two = ''
this.three = ''
this.four
}
}
console.log(Object.keys(Reflect.construct(Foo, [])))
推荐阅读
- typescript - 使用斜线参数“/”调用 Api
- bitbucket - 由于身份验证问题,Sourcetree 无法推送到 bitbucket 存储库
- c# - 找不到类型或命名空间名称“HttpResponseMessage”
- django - heroku python 应用程序中没有名为“pyrebase”的模块
- node.js - RSYNCWRAPPER:rsync 以代码 12 退出
- spring - Spring Batch ResourcelessTransactionManager 与persistence.xml 混淆?
- javascript - Node.js mongoose 连接错误
- python - pandas:将所有具有 2 个值的列转换为 True/False
- network-programming - RPC 调用“svc_fd_create”在 SOLARIS 上失败,并出现“错误文件号”错误
- python - 调用 subprocess.call(...) 产生错误“[WinError 2] System can't find the specified file”