在TypeScript中获取从某种类型派生的类型属性的属性值?
问题描述:
我有一个抽象类Section
将用于表示可以是有效的或无效的文档的一部分。这些部分也可以嵌入部分。如果部分包含无效的内部部分,则该部分无效。在TypeScript中获取从某种类型派生的类型属性的属性值?
我创建的类ASection1
和ASection2
为使用它们作为MySection
内部部分中,向其中验证过程是通过performValidation()
装置调用的目的。
如何获取从MySection类派生的类型的属性。我需要关于抽象类反射逻辑的帮助,如下所述。
abstract class Section {
constructor(public name: string) {
}
performValidation(): boolean {
let result: boolean = true;
//HELP IS NEEDED HERE!!!
//get all properties of this instance
//whose type inherit from "Section"
//and execute Validate() on each of them
//one at a time, if any of them returns
//false, return false.
return this.Validate();
}
abstract Validate(): boolean;
}
class ASection1 extends Section {
constructor() {
super("Section example 1");
}
Validate(): boolean {
//validation logic goes here
}
}
class ASection2 extends Section {
constructor() {
super("Section example 2");
}
Validate(): boolean {
//validation logic goes here
}
}
class MySection extends Section {
constructor() {
super("My Section");
}
subsection1: ASection1;
subsection2: ASection2;
prop1: number;
Validate(): boolean {
return this.prop1 > 100;
}
}
//run
let mySect = new MySection();
mySect.prop1 = 101;
mySect.subsection1 = new ASection1();
mySect.subsection2 = new ASection2();
mySect.performValidation();
谢谢。
答
如果您有两个或更多相同类型和相同含义的属性每次使用array而不是每个属性。我为每个小节添加小节数组。在验证中,我检查每个小节,如果任何小节验证失败循环返回false,如果没有小节验证失败验证继续通过验证自己。
abstract class Section {
protected subsections: Array<Section> = [];
constructor(public name: string) {
}
performValidation(): boolean {
let result: boolean = true;
for (var i = 0; i < this.subsections.length; i++) {
if (!this.subsections[i].Validate()) {
return;
}
}
return this.Validate();
}
public addSubsection(section: Section) {
this.subsections.push(section);
}
abstract Validate(): boolean;
}
class ASection1 extends Section {
constructor() {
super("Section example 1");
}
Validate(): boolean {
//validation logic goes here
}
}
class ASection2 extends Section {
constructor() {
super("Section example 2");
}
Validate(): boolean {
//validation logic goes here
}
}
class MySection extends Section {
constructor() {
super("My Section");
}
prop1: number;
Validate(): boolean {
return this.prop1 > 100;
}
}
//run
let mySect = new MySection();
mySect.prop1 = 101;
mySect.addSubsection(new ASection1());
mySect.addSubsection(new ASection2());
mySect.performValidation();
为什么你不只是将部分存储在一个Map数组中,而不是未知的单个属性? –