Aidenboss
V2EX  ›  Node.js

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

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

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