如何迭代一个类的不存在的成员? [英] How to iterate over non existent member of a class?

查看:39
本文介绍了如何迭代一个类的不存在的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何实现以下原型代码:

How do I achieve the following prototype-code:

class test {
    a: number;
    b: boolean;
    c: string;
}

for (const so in test)
    so, //'a', 'b', 'c'...
    //so.type //'number', 'boolean', 'string'...

我不知道如何获取类型,但是我尝试创建一个新对象并对其进行迭代以获取名称,但显然这不起作用,因为类成员未初始化.

I don't have any idea how to get the type however I tried creating a new object and iterating over it for the names but obviously this didn't work since the class members were left uninitialized.

推荐答案

正如问题评论中所建议的,元数据可以在一定程度上使用,但它很混乱.

As suggested in the comment on the question, metadata could be used to some degree but it is messy.

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

First the decorator has to store all key names in a list because the properties do not actually exist on the prototype:

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.这将是类型构造函数,而不是名称.

To iterate the list can be retrieved from the symbol properties symbol slot and the getMetadata function can be used to get the generated design:type. This will be the type constructor, not the name.

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

这应该打印如下内容:

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

<小时>

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


Note that the compiler settings have to contain decorators & metadata flags:

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

这篇关于如何迭代一个类的不存在的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆