samedi 25 février 2017

javascript reflection. How to inject value to not required variable

What is the best way to inject value to not required variable? Please see following code.

export interface IApprove {
  approve():boolean;
}

export class FirstImplementation implements IApprove {
  approve():boolean {
    return true;
  }
}

export class SecondImplementation implements IApprove {
  private data:number;

  approve():boolean {
    return this.data > 1;
  }
}

function approve(guardsClasses:Array<any>, data:number):boolean {
  guardsClaases.forEach((guardClass) => {
    let guard = injector.get(guardClass); // this is some abstract injector that create instance from class
    // here I would like to check whether guard instance have "data" variable. If so - pass data value.
    let result = guard.approve();
    if (!result) {
      return false
    }
  });
  return true;
}

approve([FirstImplementation, SecondImplementation], 2);

1) I could use Object.hasOwnProperty, but it seems to work only when property is initialized. In other case it returns null

2) I could force setting value on each guard, but type script compiler will throw error since it will not fit IApprove interface.





Aucun commentaire:

Enregistrer un commentaire