RT,求各位大佬解答下。 我有一个类:
class Test {
id: Number
name: String
}
想问下如何获取:["id", "name"] 谢谢!!!
![]() |
3
EPr2hh6LADQWqRVH 2019-05-31 23:57:37 +08:00
|
![]() |
4
IsaacYoung 2019-05-31 23:58:13 +08:00
new Test().id ?
|
![]() |
5
zhwithsweet 2019-06-01 00:00:21 +08:00 via iPhone
get getId()
|
6
Aidenboss OP @avastms 如果使用 Object.getOwnPropertyNames(Test) 的话,返回了 [ 'length', 'prototype', 'name' ]
如果时候用 Object.getOwnPropertyNames(new Test()) 的话,返回了 [] |
7
Aidenboss OP |
![]() |
8
zhwithsweet 2019-06-01 00:12:28 +08:00 via iPhone
那 object.keys 就行
|
9
zbinlin 2019-06-01 00:23:23 +08:00
keyof Test
|
![]() |
10
sneezry 2019-06-01 00:25:02 +08:00 via iPhone
我觉得得看你 tsconfig 怎么配置的,然后看看 class 被生成成什么样,才能想办法怎么拿
|
![]() |
11
wly19960911 2019-06-01 00:25:23 +08:00
![]() 源代码: class Test { id: number name: string constructor(id: number, name: string) { this.id = id; this.name = name; } } 编译结果: var Test = /** @class */ (function () { function Test(id, name) { this.id = id; this.name = name; } return Test; }()); |
![]() |
12
wly19960911 2019-06-01 00:29:46 +08:00
https://jkchao.github.io/typescript-book-chinese/tips/metadata.html
有兴趣的话,可以看看这个,angular 反射出注解的原理和这个差不多。 |
![]() |
13
wly19960911 2019-06-01 00:33:42 +08:00
Object.getOwnPropertyNames(new Test())
另外 这个是能返回 ["id", "name"] 的,虽然我不敢用这个。因为无关的东西也可能反射出来。 比如我有个 private 变量,也会被这个取出来。所以这个并不是很实用。 |
![]() |
14
FrankFang128 2019-06-01 02:18:11 +08:00
Object.keys(Test.prototype)
|
![]() |
15
beginor 2019-06-01 07:30:48 +08:00 via Android
`reflect-metadata` 了解一下?
|