Angular 将子类的实例从父变量分配给子变量

Angular 将子类的实例从父变量分配给子变量,angular,typescript,Angular,Typescript,我有一个父类,叫做MyClass。它有两个子项,定义为: export class MyChildFirst extends MyClass {...} export class MyChildSecond extends MyClass {...} MyClass的每个实例都属于两个子类中的一个子类。然后我有一个MyClass数组。我在数组中循环,我想将那些属于MyChildSecond的MyClass实例分配给MyChildSecond的数组 var bigArray = new Arra

我有一个父类,叫做MyClass。它有两个子项,定义为:

export class MyChildFirst extends MyClass {...}
export class MyChildSecond extends MyClass {...}
MyClass的每个实例都属于两个子类中的一个子类。然后我有一个MyClass数组。我在数组中循环,我想将那些属于MyChildSecond的MyClass实例分配给MyChildSecond的数组

var bigArray = new Array<MyClass>();
// ...
// populate that array
// ...
var smallArray = new Array<MyChildSecond>();
for (var element of bigArray) {
   if (element.constructor.name === 'MyChildSecond') {
      smallArray[smallArray.length] = element;
   }
}
var bigArray=new Array();
// ...
//填充该数组
// ...
var smallArray=新数组();
for(bigArray的var元素){
if(element.constructor.name=='MyChildSecond'){
smallArray[smallArray.length]=元素;
}
}

但是,这不起作用,因为即使代码确保仅将MyChildSecond分配给数组,它仍将“元素”视为MyClass,因此无法将其分配给包含MyChildSecond的变量。如何实现这一点?

您可以对TypeScript中的类使用
instanceof

var smallArray = bigArray.filter(
                   (element)=>element instanceof MyChildSecond
                 ) as MyChildSecond[];

您可以将
instanceof
与TypeScript中的类一起使用

var smallArray = bigArray.filter(
                   (element)=>element instanceof MyChildSecond
                 ) as MyChildSecond[];

您的代码看起来很好,在这里工作:它在我的Angular应用程序的上下文中不工作。您的代码看起来很好,在这里工作:它在我的Angular应用程序的上下文中不工作。这将创建一个MyClass数组,其中只包含作为MyChildSecond实例的bigArray元素。我需要MyChildSecond数组的形式,而不是只包含MyChildSecond的MyClass数组。这意味着我不能访问MyChildSecond独有的元素,这是我的目标。@chodobaggins,我觉得这听起来不太对。我已经更新了我的答案来澄清类型问题。无论出于何种原因,这返回了一个空数组,我真的很困惑,我认为这是因为即使数组中的元素是MyChildFirst和MyChildSecond,它们都存储为MyClass,这将创建一个MyClass数组,该数组只包含作为MyChildSecond实例的bigArray元素。我需要MyChildSecond数组的形式,而不是只包含MyChildSecond的MyClass数组。这意味着我不能访问MyChildSecond独有的元素,这是我的目标。@chodobaggins,我觉得这听起来不太对。我更新了我的答案以澄清类型问题。无论出于何种原因,这返回了一个空数组,我真的很困惑,我认为这是因为即使数组中的元素是MyChildFirst和MyChildSecond,它们存储为MyClass,所以它们不符合instanceof条件。