在创建一个以对象作为参数的实例后,我想实现两件事:
首先,遍历参数的属性并将其添加到实例中,如果它与在构造函数上方声明的此属性方式完全相同。有没有一种快速的方法,我是否必须一项一项地检查?
其次,我想检查是否定义了每个声明的属性,如果没有定义则设置一个默认值。
var data = {
langs: ["de","en","fr"],
lesson: {
de: "Einführung",
en: "Introduction"
},
keywords: []
}
class Video {
langs: Array<string>;
lesson: object;
topic: object;
intro: object;
keywords: Array<Keyword>;
constructor (data) {
for (let prop in data) {
if (/*data.s is of type as declared above constructor()*/) {
this[prop] = data[prop];
} else {
throw "Type of {{prop}} is invalid";
}
}
for (let prop in /*All the props defined above constructor()*/) {
if (!this.hasOwnProperty(prop)) {
//Set default value;
}
}
}
}
var video = new Video(data);
最佳答案
Is there a quick way to do so are do I have to check this one by one?
使用类型注释,例如改变
constructor (data) {
到
constructor (data: { langs : string[] /* so on */}) {
i want to check if each of the declared properties is defined and set a default value if not.
使用 strictNullChecks 将逻辑移出代码:https://basarat.gitbooks.io/typescript/content/docs/options/strictNullChecks.html
关于javascript - 评估类构造函数中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45850237/