Angular 5 阻止向 class 添加道具

Angular 5 prevent adding props to class

我有这个class

export class Alpha {
     propAlpha?:string;

     constructor(){
     }

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

}

有些 rest 调用给我一个像这样的对象(响应):

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

我只需要将此对象的有效属性推送到 Alpha,所以我做到了

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!
     */
});

问题是 _someUnwanted 被添加到我的 class。 我怎样才能防止这种情况发生?

我需要检查 Alpha 中有哪些键..

可能是这样的?

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

真的很糟糕,但我通过这样做解决了:

export enum AlphaPublicKeys {
    propAlpha
}

let myAlpha = new Alpha();
_.each(Object.keys(response), key => {

    if(key in AlphaPublicKeys){
        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!
     */
});

希望对您有所帮助!

不需要声明单独枚举的不同方法是在其构造函数中声明 class 成员。那么您的 Alpha class 将如下所示:

export class Alpha {
     constructor(public propAlpha?: string){}

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

分配属性不会改变

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