首页 > 解决方案 > 在数组 angular 5 中添加两种不同类型的对象

问题描述

我有两个不同的数组,英雄:Hero[] 和怪物:Monster[]。它们共享一个名为 totalInitiative 的公共字段。这两个数组需要放入同一个数组中,并根据它们的totalInitiative 进行排序。

我试图实现的目标是这样的:

Array[hero1, hero2, hero3, monster1, monster2] 

我创建了一个名为 Participant 的超类:

import {Participant} from './participant';

export class Hero extends Participant{
id: number;
name: string;
player: string;
hitPoints: number;
armor: number;
initModif: number;
imageUrl: string;
totalInitiave: number;
}

import {Participant} from './participant';

export class Monster extends Participant{
id:number;
name: string;
hitPoints: number;
armor: number;
initModif: number;
imageUrl: string;
}

export class Participant{

}

我没有在 Participant 中添加公共字段,因为我有一个 Hero 和一个 Monster 组件,我需要这些公共属性来添加一个新的 Hero/Monster。

现在我需要调整我的 Encounter 模型,使其包含一个包含 Hero[] 和 Monster[] 的 Participant[]

import {Hero} from './hero';
import {Monster} from './monster';
import {Participant} from './participant';

export class Encounter {
id: number;
name: string;
participants: Participant[ Hero[] Monster[]]; //Doesn't work
}

我什至不确定这是正确的方法吗?

标签: angulartypescriptcomponents

解决方案


您的数组的类型需要是Hero和的联合Monster

const participants: (Hero | Monster)[] = [];

这是一个带有基本排序的缩减示例......

class Hero {
  constructor(public initiative: number) { };
}

class Monster {
  constructor(public initiative: number) { };
  evil = 5;
}

const heroes = [
  new Hero(5),
  new Hero(3)
];

const monsters = [
  new Monster(2),
  new Monster(7)
];

const participants: (Hero | Monster)[] = heroes.concat(monsters);

const sorted = participants.sort((a, b) => a.initiative - b.initiative);

console.log(sorted);

推荐阅读