28

我试图发现一种将多个接口组合成一个抽象类的模式。目前我可以通过 组合多个接口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: "" });
4

2 回答 2

44

在与实例成员相同的接口上声明构造函数并没有多大意义——如果您要动态传递一个类型以在构造函数中使用,那么将受到限制的是类的静态部分。你想要做的可能是这样的:

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);

另请参阅带有构造签名的 typescript 接口如何工作?

于 2013-07-25T18:47:54.853 回答
0

以下是继承多个接口的解决方案示例:

type ShowAllWithTypography =  TypographyClampProps & ShowAllProps

interface Props extends ShowAllWithTypography
于 2022-02-05T00:48:24.093 回答