如何迭代班级的不存在成员



如何实现以下原型编码:

class test {
    a: number;
    b: boolean;
    c: string;
}
for (const so in test)
    so, //'a', 'b', 'c'...
    //so.type //'number', 'boolean', 'string'...

我不知道如何获得类型,但是我尝试创建一个新对象并迭代名称,但是显然这是不起作用的,因为班级成员未经启发。

如该问题的评论所建议的,元数据可以在某种程度上使用,但这很混乱。

首先,装饰器必须在列表中存储所有关键名称,因为这些属性实际上并不存在于原型上:

import 'reflect-metadata';
const propertiesSymbol = Symbol('properties');
const metadata = (target: any, key: string) => {
    let list = <string[] | undefined>target[propertiesSymbol];
    if (list == undefined)
        list = target[propertiesSymbol] = [];
    list.push(key);
};

这是在类的属性上使用的:

class Test {
    @metadata
    a!: number;
    @metadata
    b!: boolean;
    @metadata
    c!: string;
}

可以从符号属性符号插槽中检索列表,并且getMetadata函数可用于获取生成的design:type。这将是类型的构造函数,而不是名称。

for (const key of (Test.prototype as any)[propertiesSymbol])
    console.log(Reflect.getMetadata("design:type", Test.prototype, key));

这应该打印出:

[Function: Number]
[Function: Boolean]
[Function: String]

请注意,编译器设置必须包含装饰器&amp;元数据标志:

"compilerOptions": {
    // ...
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
}

最新更新