loop over own properties in base class in typescipt

Viewed 62

I'm trying to design a validation algorithm for a complex data model in Typescript. In its simplified form, I've come up with a class model like this:

export abstract class Validatable {

    protected errors: string[];

    isValid(): boolean {
        let result = true;
        for each property (which may or may not be an array) in this instance which extends Validatable {
            if (Array(property)) {
                if (!property.every(item=>item.isValid()) {
                    return false;
                }
            } else {
                if (!property.isValid()) {
                    return false;
                }
            }
        }

        return this.errors.length === 0;
    }
}

export class B extends Validatable{
    name: string;
}

export class A extends Validatable{
    name: string;
    Bs: B[];
}

I'm having trouble figuring out how to set up looping over properties (line 'for each property). Or if it's even possible.

The idea is to call isValid on an instance of class A which in turn will call isValid on all constituent properties instead of repeating pretty much the same code in each class.

2 Answers

You can use the isArray() function to check if the property is an Array.

For example:

isArray([1,2,3]) // returns true

isArray(123) // returns false

properties will contain the list of all the properties of the class. You can use them to create your logic of validation or anything.

class Validatable {

  name: string = "Siraj";
  nums: number[] = [1, 2, 3]

  isValid () :boolean {
    const properties:string[] = Object.getOwnPropertyNames(this);
    console.log(properties);
    return true;  
  }


}

class A extends Validatable {
  hello = "Greet"
}

let a = new A();

a.isValid();
// logs ["name", "nums", "hello"]

Playground Link

Related