Javascript 在Typescript中获取类的所有非函数/修饰属性?
我需要获得typescript类的所有属性,这些属性不是函数。我不确定属性也将被修饰这一事实是否可以加快识别速度(如果Typescript提供了任何使用反射来识别修饰属性的方法?) 最终目标是使用这些作为键来查找相应的值,然后对这些值进行验证(因此示例中包含注释)。例如:Javascript 在Typescript中获取类的所有非函数/修饰属性?,javascript,typescript,Javascript,Typescript,我需要获得typescript类的所有属性,这些属性不是函数。我不确定属性也将被修饰这一事实是否可以加快识别速度(如果Typescript提供了任何使用反射来识别修饰属性的方法?) 最终目标是使用这些作为键来查找相应的值,然后对这些值进行验证(因此示例中包含注释)。例如: class A { @IsString() foo: string = "foo"; @IsNumber() c: number = 2; d: ()=>... } let a:
class A {
@IsString()
foo: string = "foo";
@IsNumber()
c: number = 2;
d: ()=>...
}
let a:A = new A();
let properties = getPropertiesToValidate(a);
properties.forEach(p=>{
value = a[p];
//validate the value.
});
更新
Per@Titian comments最简单、最有效的方法是创建一个元类实例。元类镜像修饰类,但只存储在原始类上修饰的属性。我们将为相应的修饰类创建一个元类实例,并将className
设置为constructor.name
,然后只将修饰的属性添加到数组中。如果有人知道更简单的方法,请发表评论
这是我心目中的当前实施:
/**
* MetaClass stores the property names of the
* corresponding decorated class. These can
* then be used to lookup validation contexts
* during object validation.
*/
class MetaClass {
/**
* The name of the decorated class.
*/
public className: string;
/**
* The properties that were decorated.
*/
public properties: string[] = [];
constructor(className: string) {
this.className = className;
}
addProperty(property: string) {
if (!this.properties.includes(property)) {
this.properties.push(property);
}
}
}
属性是否在您的控制之下?如果是这样的话,您可以修改它们来收集它们应用到的字段。是的,有效地-现在就完成验证框架:我正在考虑为每个类构造函数名称创建一个键,然后使用它来查找附加了验证装饰器的属性,但我想我会先检查是否有一种更短但同样有效的方法。据我所知,没有简单的方法可以做到这一点,但其他人可能更清楚:)是的,我希望有某种直接查找方法(避免基于类型的筛选),但我有一种感觉,在应用decorator期间创建元数据将是最简单、最有效的解决方案。