【发布时间】:2017-08-23 00:49:32
【问题描述】:
我不知道如何在 typescript 中定义类的集合类型:
当我编译以下代码时,出现错误:
class Wall{
brick: string;
constructor(){
this.brick = "jolies briques oranges";
}
// Wall methods ...
}
class Critter {
CritterProperty1: string[];
CritterProperty2: string;
constructor() {
this.CritterProperty1 = "n ne e se s so o no".split(" ");
}
// Critter methods ...
}
type legendObjectType = Critter | Wall;
interface Ilegend {
[k: string]: legendObjectType;
}
// i've got an issue to define the type of 'theLegend' Object
let theLegend: Ilegend = {
"X": Wall,
"o": Critter
}
错误 TS2322: Type '{ "X": typeof Wall; “o”:Critter 的类型; }' 不是 可分配给类型“Ilegend”。
虽然我可以编译它,但如果“班级墙”是空的。
有人知道如何定义此类集合的类型吗?
让传奇 = { “X”:墙, “o”:小动物}
(这是eloquent javascript第7章的一个例子,比我尝试用打字稿转录)
编辑
我完成了 Rico Kahler 的回答,用一个抽象类来避免使用联合类型
abstract class MapItem {
originChar: string;
constructor(){}
}
class Wall extends MapItem {
brick: string;
constructor(){
super();
this.brick = "jolies briques oranges";
}
// Wall methods ...
}
class Critter extends MapItem {
CritterProperty1: string[];
CritterProperty2: string;
constructor() {
super();
this.CritterProperty1 = "n ne e se s so o no".split(" ");
}
// Critter methods ...
}
interface Ilegend {
[k: string]: new () => MapItem;
}
let theLegend: Ilegend = {
"X": Wall,
"o": Critter
}
谢谢。
【问题讨论】:
标签: object typescript collections types