Angular 2打字稿动态组件类型

时间:2018-03-13 19:06:23

标签: angular typescript

我有一个包含两种类型对象的数据数组。

   this.alerts = [{
      type: "a",
      aField: "infoSpecific"
    },
    {
      type: "b",
      bField: "warningSpecific"
    }];

我想根据数组数据动态创建组件:

 this.notifications.forEach(alert => {
      const component = this.getComponent(alert);
      const factory = this.resolver.resolveComponentFactory(component);

      const ref = this.container.createComponent(factory);
      ref.instance.data = n;
    });


  getComponent(alert: AlertInfoComponent | AlertWarningComponent): Type<AlertInfoComponent | AlertWarningComponent> {
    switch (alert.type) {
      case "a":
        return AlertInfoComponent;
      case "b":
        return AlertWarningComponent;
    }
  }

forEach内部,组件变量的类型为Type<AlertInfoComponent | AlertWarningComponent>。如何让打字稿在每次迭代中知道正确的类型?

1 个答案:

答案 0 :(得分:0)

尝试:instanceof和`

if (myObject instanceof Type) {
  console.log("myObject *is* an instance of Type!");
} else {
  console.log("Oops! myObject is not an instance of Type...");
}

typeof

// Using typeof in an EXPRESSION:
var x = 5;  
var y = typeof x; // y will have the string "number" as value

// Using typeof in an TYPE QUERY
// (or... as I like to say, variable declaration):
var a = 9; // a is a number
var b: typeof a; // b will be declared as a number as well

b = "a string"; // yields an error, as b is a number:
                // "The type 'string' is not assignable to type 'number'."