我正在尝试在 typescript 中模拟 OOP 概念。我有 Java 背景。我面临的问题是,我正在尝试创建一款棋盘游戏。我有酒店、 jail 、宝藏等细胞类型。它们都有一个共同的属性,称为类型数的数量。所以我创建了一个名为 CellType 的接口(interface)并将其实现到上面提到的各个类(酒店、宝藏等) 有一个名为 Board 的类,我想在其中初始化并声明预定义单元类型的数组。像这样的事情:
var cell[:CellType]; //declaration
Hotel = new Hotel(200);
cell = [Hotel1,Treasure1,Jail1,Hotel2..] //initialization
在java中我们可以做到:
interface CellType{ public integer amount};
class Hotel implements CellType;
class Jail implements Celltype;
// in main class
ArrayList<CellType> cellTypes = new ArrayList<CellType>;
Hotel Taj = new Hotel();
cellTypes.add(Taj);
Jail jail = new Jail();
cellTypes.add(jail);
那么,如何像 Java 中那样声明继承同一个父类(super class)的多个子类的数组?
最佳答案
接口(interface)/类:
interface CellType { amount: number };
class Hotel implements CellType {
// This concise syntax creates the public property
// and assigns to it the value passed into the
// constructor
constructor(public amount: number) { }
}
class Jail implements CellType {
constructor(public amount: number) { }
}
用法:
let cellTypes: Array<CellType> = []; // Or let cellTypes: CellType[] = [];
let taj = new Hotel(100);
cellTypes.push(taj);
let jail = new Jail(200);
cellTypes.push(jail);
你可以这样更简洁:
let cellTypes: Array<CellType> = [new Hotel(100), new Jail(200)];
关于javascript - 如何在typescript中模拟多态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097929/