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

标签 javascript angular typescript

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

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

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

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/

相关文章:

javascript - 使用 Typescript knockout 复选框

unit-testing - Jasmine 路线 spy - 未定义不是一个对象(评估 'navigate.calls.mostRecent().args' )

javascript - vscode 在打开的文件上自动折叠

angular - ngStyle 没有得到应用

PHP 和 Angular 2 - "live"使用/自己的 API 和数据库直接消息传递

c# - 如何保持 AngularCLIServer 在使用 Angular 7 的 asp.net 核心构建之间运行

javascript - 使用 NodeJS/npm 调用本地 JS 包

javascript - 多个按钮和模式

javascript - in querySelector : how to get the first and get the last elements? 在dom中使用什么遍历顺序?

javascript - 每 5 分钟显示一次 div javascript