【发布时间】:2015-08-10 05:19:16
【问题描述】:
我想知道是否可以声明类函数的返回类型,该返回类型将在实例化时通过它的构造函数传递给类。
我使用“creature”类作为生物的通用基础,并将其细节(定义为接口“creatureSpecs”)传递给构造函数。
生物的“行动”功能是可变的,取决于它是什么类型的生物。 'act' 总是会返回一个 'Action' - 它只需要一个特定于生物的代码路径来做到这一点。
所以 A)我可以在类本身上声明通过构造函数传递的函数的返回类型吗?
B) 这是错误的做法吗?
示例代码:
interface Action {type: string; direction: string;}
interface Creaturespec{ energy: number; direction: string; act: Function; preyseen?: Array<any>};
var Creaturespecs: {[id: string]: Creaturespec } = {}
class creature{
public energy: number;
public direction: string;
public act: Function;
public originChar : string;
public preyseen: Array<any>;
constructor(spec: Creaturespec, originChar: string) {
this.energy = spec.energy;
this.direction = spec.direction;
this.act = spec.act;
this.originChar = originChar
this.preyseen = spec.preyseen;
}
};
【问题讨论】:
标签: typescript