Aidenboss
V2EX  ›  Node.js

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

  •  
  •   Aidenboss · May 31, 2019 · 8519 views
    This topic created in 2572 days ago, the information mentioned may be changed or developed.

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

    class Test {
        id: Number
        name: String
    }
    

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

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

    比如我有个 private 变量,也会被这个取出来。所以这个并不是很实用。
    FrankFang128
        14
    FrankFang128  
       Jun 1, 2019
    Object.keys(Test.prototype)
    beginor
        15
    beginor  
       Jun 1, 2019 via Android
    `reflect-metadata` 了解一下?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1733 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 16:21 · PVG 00:21 · LAX 09:21 · JFK 12:21
    ♥ Do have faith in what you're doing.