Search code examples
classtypescriptangular5extend

Angular 5 prevent adding props to class


I have this class

export class Alpha {
     propAlpha?:string;

     constructor(){
     }

     setProp(key: string, value: string) {
        this[key] = value;
     }

}

Some rest call gives me an object (response) like this:

{
    propAlpha: "foo",
    _someUnwanted: "bar"
}

I need to push only valid props of this object into Alpha, so I did

let myAlpha = new Alpha();
_.each(Object.keys(response), key => {
    validProp(response[key]) && myAlpha.setProp(key, response[key]);
    /**
     * validProp() checks if value matches some criteria.
     * So even if "propAlpha" is in "Alpha" it may be 
     * excluded for some other reason!
     */
});

the problem is that _someUnwanted is added to my class. How can I prevent that?

I'd need to check which keys are in Alpha..

maybe like this?

if(key in myAlpha) {
   myAlpha.setProp(key, response[key]);
}

Solution

  • Different approach that doesn't require declaring separate enum is to declare class members inside it's constructor. Then your Alpha class would look like this:

    export class Alpha {
         constructor(public propAlpha?: string){}
    
         setProp(key: string, value: string) {
            if (key in this) this[key] = value;
         }
    }
    

    assigning properties wouldn't change

    _.each(Object.keys(response), key => {
        validProp(response[key]) && myAlpha.setProp(key, response[key]);
    });