V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Aidenboss
V2EX  ›  Node.js

TypeScript 如何获取 class 类的成员变量呢?

  •  
  •   Aidenboss · 2019-05-31 23:38:31 +08:00 · 7739 次点击
    这是一个创建于 1784 天前的主题,其中的信息可能已经有所发展或是发生改变。

    RT,求各位大佬解答下。 我有一个类:

    class Test {
        id: Number
        name: String
    }
    

    想问下如何获取:["id", "name"] 谢谢!!!

    15 条回复    2019-06-01 07:30:48 +08:00
    des
        1
    des  
       2019-05-31 23:48:12 +08:00
    这样?
    console.log(Test.id, Test.name)
    Aidenboss
        2
    Aidenboss  
    OP
       2019-05-31 23:48:50 +08:00
    @des 不是,我想要动态获取。不是写死在代码中的
    IsaacYoung
        4
    IsaacYoung  
       2019-05-31 23:58:13 +08:00
    new Test().id ?
    zhwithsweet
        5
    zhwithsweet  
       2019-06-01 00:00:21 +08:00 via iPhone
    get getId()
    Aidenboss
        6
    Aidenboss  
    OP
       2019-06-01 00:00:24 +08:00
    @avastms 如果使用 Object.getOwnPropertyNames(Test) 的话,返回了 [ 'length', 'prototype', 'name' ]
    如果时候用 Object.getOwnPropertyNames(new Test()) 的话,返回了 []
    Aidenboss
        7
    Aidenboss  
    OP
       2019-06-01 00:00:57 +08:00
    @IsaacYoung
    @zhwithsweet
    不是写死代码的这种哈
    zhwithsweet
        8
    zhwithsweet  
       2019-06-01 00:12:28 +08:00 via iPhone
    那 object.keys 就行
    zbinlin
        9
    zbinlin  
       2019-06-01 00:23:23 +08:00
    keyof Test
    sneezry
        10
    sneezry  
       2019-06-01 00:25:02 +08:00 via iPhone
    我觉得得看你 tsconfig 怎么配置的,然后看看 class 被生成成什么样,才能想办法怎么拿
    wly19960911
        11
    wly19960911  
       2019-06-01 00:25:23 +08:00
    放弃吧,没有反射,有也要自己填值,如果你有这个心情手填反射的信息是可以的,我看过 angular 一些依赖注入和反射的实现原理。
    源代码:
    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;
    }());
    wly19960911
        12
    wly19960911  
       2019-06-01 00:29:46 +08:00
    https://jkchao.github.io/typescript-book-chinese/tips/metadata.html
    有兴趣的话,可以看看这个,angular 反射出注解的原理和这个差不多。
    wly19960911
        13
    wly19960911  
       2019-06-01 00:33:42 +08:00
    Object.getOwnPropertyNames(new Test())
    另外 这个是能返回 ["id", "name"] 的,虽然我不敢用这个。因为无关的东西也可能反射出来。

    比如我有个 private 变量,也会被这个取出来。所以这个并不是很实用。
    FrankFang128
        14
    FrankFang128  
       2019-06-01 02:18:11 +08:00
    Object.keys(Test.prototype)
    beginor
        15
    beginor  
       2019-06-01 07:30:48 +08:00 via Android
    `reflect-metadata` 了解一下?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4281 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 10:11 · PVG 18:11 · LAX 03:11 · JFK 06:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.