【发布时间】:2017-03-24 02:49:48
【问题描述】:
我在 type script 有一门课:
export class Child {
name:string;
age:number;
}
我想强制类实例只具有类声明所具有的属性。
例如,如果我从 firebase 获取一个对象:
myFirebaseService.getChild(id).then(function(child){
var currentChild = new Child(child);
})
所以当对象是:{name:"ben", color:"db"}时,我希望结果是:
currentChild = {"name":"ben"}
因为“color”不是“child”的字段。
我试过了:
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 新功能可能对您很方便。
-
@AlekseyL。不,因为他的问题是运行时问题。
-
可能有帮助的类似(不相同)问题 - stackoverflow.com/questions/22875636/…
标签: typescript constructor copy-constructor