gpt4 book ai didi

javascript - 评估类构造函数中的参数

转载 作者:太空狗 更新时间:2023-10-29 19:34:10 24 4
gpt4 key购买 nike

在创建一个以对象作为参数的实例后,我想实现两件事:

首先,遍历参数的属性并将其添加到实例中,如果它与在构造函数上方声明的此属性方式完全相同。有没有一种快速的方法,我是否必须一项一项地检查?

其次,我想检查是否定义了每个声明的属性,如果没有定义则设置一个默认值。

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com