I'm working with a TypeScript class:
export class Child {
name:string;
age:number;
}
I'm looking to restrict class instances to only have properties declared in the class.
For instance, if I retrieve an object from Firebase:
myFirebaseService.getChild(id).then(function(child){
var currentChild = new Child(child);
})
So when the object is: {name:"ben", color:"db"}, I want the result to be:
currentChild = {"name":"ben"}
Because "color" is not a field of "child".
I attempted the following approach:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
for (var prop in tempChild) {
this[prop] = tempChild[prop];
}
}
}
}
But it doesn't work as expected. The "currentChild" still ends up with all fields attached to the class instance.
(Of course, I could use the following code:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
this.name = tempChild.name;
this.age = tempChild.age;
}
}
}
, but since my actual class has numerous fields, I prefer a shorter solution)