我有类型的脚本类:打字稿 - 传递给构造器,整个对象
export class Child {
name:string;
age:number;
}
我想迫使类实例有一个类声明只有性能。
例如,如果我从火力得到一个对象:
myFirebaseService.getChild(id).then(function(child){
var currentChild = new Child(child);
})
所以当对象是:{名称:“奔”,颜色:“DB”},我希望得到的结果是:
currentChild = {"name":"ben"}
Becouse“color”不是“孩子”的字段。
我尝试这样做:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
for (var prop in tempChild) {
this[prop] = tempChild[prop];
}
}
}
}
但它不能帮助。 “currentChild”获取所有字段并将它们附加到类实例。
(当然,我可以使用下面的代码:
export class Child {
name:string;
age:number;
constructor(tempChild:Child = null) {
if (tempChild){
this.nam = tempChild.name;
this.age =tempChild.ageÏ;
}
}
}
,但我的心里话类有许多领域,我想短码)
我认为typescript 2.1的新[keyof](https://github.com/Microsoft/TypeScript/pull/11929)功能可能对您很方便。 –
@AlekseyL。不,因为他的问题是运行时问题。 –