我正在尝试发现一种将多个接口组合成一个抽象类的模式。目前我可以通过implements
组合多个接口,但接口不能声明构造函数。当我必须引入一个构造函数时,我被迫使用一个抽象类。当我使用抽象类时,我必须重新声明整个复合接口!当然我错过了什么?
interface ILayerInfo {
a: string;
}
interface ILayerStatic {
b(): string;
}
class Layer implements ILayerInfo, ILayerStatic {
constructor(info: ILayerInfo);
a: string;
b(): string;
}
答案:使用new
:
interface Layer extends ILayerInfo, ILayerStatic {
new(info: ILayerInfo);
}
// usage: new Layer({ a: "" });
在与实例成员相同的接口上声明构造函数并没有多大意义 - 如果要在构造函数中动态传入一个类型,那么它将是受限制的类的静态端。你想要做的可能是这样的:
interface Colorable {
colorize(c: string): void;
}
interface Countable {
count: number;
}
interface ColorCountable extends Colorable, Countable {
}
interface ColorCountableCreator {
new(info: {color: string; count: number}): ColorCountable;
}
class ColorCounted implements ColorCountable {
count: number;
colorize(s: string) { }
constructor(info: {color: string; count: number}) {
// ...
}
}
function makeThings(c: ColorCountableCreator) {
var results: ColorCountable[];
for(var i = 0; i < 10; i++) {
results.push(new c({color: 'blue', count: i}));
}
return results;
}
var items = makeThings(ColorCounted);
console.log(items[0].count);
另见How does typescript interfaces with construct signatures work?